Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm having some annoying issues between Bootstrap/JQuery/my own CSS, tell me if this sounds like a problem you know how to fix.
I'm implementing my own "slider", with AJAX calls loading content onto the page depending on the navigation the user does. The problem comes in with my navbar. When an onhashchange event happens, I'm loading the correct content in, clearing the active class from the <li> element, and re-adding the active class to the appropriate <li> element.
Unfortunately, setting the active class isn't causing the appropriate CSS I have written to be applied, a slight darkening. There could be a million things causing THAT, I realize. But hardcoding an active class gives exactly the desired result. I don't know where the disconnect is. I ask myself, is a page loading problem getting in the way of the CSS being applied? I don't know.
Thanks in advance.
HTML:
...
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="sections nav navbar-nav">
<li>Call</li>
<li>Police</li>
<li>Charges</li>
<li>Jail</li>
<li>Courts</li>
<li>Resources</li>
</ul>
...
</div>
...
My CSS:
.navbar {
background-color: #231f20;
}
.navbar .sections>li>a:hover {
background-color: #4f4c4d;
}
/* Overriding */
.navbar a { color: #DDD !important; }
.navbar a:hover { color: #AAA !important; }
.navbar-nav>.active>a { background-color: #4f4c4d !important; }
My JS:
/* Constants */
var elem = $('.sections li a');
var pages = [];
for(i=0; i<elem.length; i++) {
//console.log(elem[i])
pages[i] = elem[i].hash;
}
var first = 0;
var last = pages.length;
...
function loadPage(hash, callback) {
/* Loads the content inside the "#main" element on the
page found at <url> into the "#main" element of the
current page. Then sets the links and buttons
accordingly. */
url = hash.split('#')[1] + '.html'
$('#main').load(url + "#main", callback);
setLinks(hash);
}
function setLinks(hash) {
for (i=0; i<=last; i++) {
if (pages[i] == hash) {
page_num = i;
}
}
var previous = page_num - 1;
var next = page_num + 1;
...
$('.sections li').removeClass('active');
$('.sections li').eq(page_num).addClass('active');
}
$(document).ready(function() {
...
$(window).on('hashchange', function() {
loadPage(window.location.hash);
});
});
You should make use of the callback functionality offered in the function loadpage. You are doing an asynchronic call, and directly applying the css. However, the page has not been updated yet (it takes some time). You should do something like this (only the updated functions):
function loadPage(hash, callback) {
/* Loads the content inside the "#main" element on the
page found at <url> into the "#main" element of the
current page. Then sets the links and buttons
accordingly. */
url = hash.split('#')[1] + '.html'
$('#main').load(url + "#main", callback);
// setLinks(hash); <-- don't do this, it will be executed to early!
}
$(document).ready(function() {
...
$(window).on('hashchange', function() {
loadPage(window.location.hash, setLinks); // <-- making use of the callback functionality
});
});
And remove the setLinks call from the loadPage function itself. By passing it in as the callback function, it will get executed once the $('#main').load is finished.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 13 days ago.
Improve this question
This question is too nuanced for me to find an answer on Google and I've been struggling with it for so long trying to find a good answer.
I want span elements to cut off with an ellipsis when they overflow a div. The problem is that this behavior only works when I set the span's display to block, but this causes the other spans who aren't long enough to overflow the div have their widths expanded, when I want them to stay only the size of their inner content.
Here's a demonstration in an online editor - try changing display from "block" to "inline" to see what I mean.
http://tpcg.io/_0UNNZM
Any help would be appreciated, I am new at css and it has been treacherous to learn so far. :)
My solution is a bit hacky. I gave the second span a classname.
<span class="secondElement">000</span>
I then set the second element to display: inline:
.secondElement {
display: inline;
}
It solved the issue. Here is the working solution: http://tpcg.io/_PJLSI5 .
Edit:
Since the elements are dynamic. I implemented the change the functionality with the help of JavaScript.
First, I add a class name spansContainer so that I can reference it with JavaScript. And I also removed the class on the second span element:
<div class="spansContainer">
<span>0000000000000000000000</span>
<br />
<span>000</span>
</div>
In the CSS, I set display to inline and added a new class block, that sets display to block:
span {
background-color: #0000ff80;
overflow: hidden;
text-overflow: ellipsis;
display: inline; /* set it to inline*/
}
/* this class is added to the span element using JavaScript */
.block {
display: block;
}
From there, I wrote the JavaScript solution:
const spansContainer = document.querySelector(".spansContainer");
const spanElements = document.querySelectorAll("span");
// add the class `block` to all span elements
// that have a width greater than the parent
// on page load.
spanElements.forEach((spanEl) => {
if (spanEl.offsetWidth > spansContainer.offsetWidth) {
spanEl.classList.add("block");
}
});
// configuration of the observer:
config = {
attributes: true,
childList: true,
characterData: true,
subtree: true,
};
// create an observer instance
var observer = new MutationObserver(function (mutations) {
// loop through the mutated span elements
mutations.forEach(function (mutation) {
const spanEl = mutation.target.parentElement;
if (spanEl.offsetWidth > spansContainer.offsetWidth) {
spanEl.classList.add("block");
} else {
// remove class 'block' if span's width is
// smaller than the div
spanEl.classList.remove("block");
}
});
});
// pass in the target node, as well as the observer options
observer.observe(spansContainer, config)
I created the codepen for the solution here: https://codepen.io/Stanleyu/pen/bGjJwxO
I am modifying some JSP files, and every time I upload a new version, if people don't update the cache, the styles are not rendered as they should be; it is looking not good and without styles applied.
To solve this problem, I have followed an example from Stack Overflow that adds a numeric value to the CSS file, preventing it from being cached in the browser. The specific link I've seen is this one:
https://wpreset.com/force-reload-cached-css/
But I've found that whenever I press F5 or navigate to other JSP's that apply the same stylesheet, the files that are part of that CSS file are always seen just before rendering. I added a GIF with a dummy example to exhibit what I mean:
Animated GIF demonstrating the problem
How could I avoid this?
Would something like the following help?
/* CSS */
.no-js #loader { display: none; }
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
|
// Js
$(window).load(function() { // Wait for window load
// Animate loader off screen
$("#loader").animate({
top: -200
}, 1500);
});
Like it is used here.
I have already been able to solve it.
In the end I have chosen to nest inside a window.onload, the document.ready like this:
window.onload = function () {
document.getElementsByTagName("html")[0].style.visibility = "visible";
var h, a, f;
a = document.getElementsByTagName('link');
for (h = 0; h < a.length; h++) {
f = a[h];
if (f.rel.toLowerCase().match(/stylesheet/) && f.href && f.href.indexOf("custom-common.css") != -1) {
var g = f.href.replace(/(&|\?)rnd=\d+/, '');
f.href = g + (g.match(/\?/) ? '&' : '?');
f.href += 'rnd=' + (new Date().valueOf());
}
}
$(document).ready(function () {
$('.main-link').click(function () {
And change the visibility of the html document. I have omitted the rest of the code, but you can get an idea. Many thanks to Robert Bradley and Adam for shedding light and helping me.
How can I make it so that within the mobile version of my site the images are not downloaded to from the web server as these are large files that are not needed and not being used and therefore severely impacting the use of the mobile version of the site. Having looking at previous threads of such nature I saw that hiding the parent of the image using code such as below can benefit.
.parent {display:block;}
.background {background-image:url(myimage.png);}
#media only screen and (max-width:480px) {
.parent {display:none;}
}
The problem being I don't want to use background image CSS for SEO issues associated with them as I like to use Schema tagging etc ..so how can I prevent an IMG tag from being downloaded, as display:none; only hides the image rather than stopping it being downloaded.
Note: This is not for copyright protection issues e.g. preventing right click etc etc but for speed and ultimately size of the downloaded content to mobile.
This solution uses CSS to prevent background-images from loading and jQuery to prevent images from loading. I'm not familiar with any CSS solution that will prevent images from loading.
JS Fiddle: http://jsfiddle.net/CoryDanielson/rLKuE/6/
If you know the images height and width (or even ratio) ahead of time you could set the background-image for a bunch of fixed size DIVs. This might be applicable for icons and layout-type images. Look at the HTML/CSS below for an example of that.
Background Images
/* hidden by default */
aside {
display: none;
}
/* Pictures load for 'big screen' users.. pcs/tablets? */
#media screen and (min-width: 750px) {
aside {
display: block;
}
.catpicDiv {
height: 100px;
width: 100px;
display: inline-block;
border: 1px solid red;
background-image: url('http://img2.timeinc.net/health/images/slides/poodle-1-400x400.jpg');
background-size: cover;
}
}
and HTML
<aside>
<div class="catpicDiv"></div>
<div class="catpicDiv"></div>
<div class="catpicDiv"></div>
</aside>
Image Elements are a different story...
I don't know of any purely CSS solution to prevent them from loading the images. So I'd solve it like this:
Define IMG tags as follows
<img src="" data-src="url-to-image.jpg" />
Then, somewhere in the head of the document you need similar javascript
1) Function to load all of the images
function loadAllTheImages() {
$("img").each(function(){
$(this).attr('src', $(this).attr('data-src'));
});
}
2) Code to determine if the user is on mobile or a PC (slow vs fast connection) and then load the images.
This code isn't bulletproof, there are much more accurate and reasonable tests than this.
$(window).load(function(){
if ( $(window).width() > 750 ) {
loadAllTheImages(); // !
} else {
$("body").append("<a id='mobileCheck' href='javascript: void(0);'>I GOTS 4G, LEMME HAVE EM!</a>");
}
});
3) As well as maybe some code to activate a button to load the images anyways? Why not, I guess... ?
$(document).ready(function(){
$('body').prepend("<h1>" + $(window).width().toString() + "</h1>");
$('body').on('click', '#mobileCheck', function(){
loadAllTheImages(); // !
$("#mobileCheck").remove();
});
});
Similar solution as here and what I hypothesized in the comments:
Delay image loading with jQuery
There is no native solution in CSS that would prevent images from loading even if you hide them or set display to none.
You have to use some JS to achieve that result. If you are familiar with JS that should not be an issue at all. There are several plugins ready to go to do what you want. You can also write your own JS because its not that difficult.
Here is my code that loads images based on the screen size:
DEMO AT CODE PEN
It works without any libraries like JQ but if you use one of those it will automatically switch to it (Tweak it to your specific needs).
JS
// use jQuery or pure JS
if (typeof jQuery !== 'undefined') {
// jQuery way
// alert("jquery");
$(function() {
$(window).on('load resize', function() {
var products = $("[data-product-image]");
products.each(function(key, value) {
var bg = null;
if (window.outerWidth < 500) return;
if (window.outerWidth < 1000) bg = $(value).data("product-image-s");
if (window.outerWidth >= 1000) bg = $(value).data("product-image");
console.log($(window).outerWidth);
$(value).css({
'background-image': 'url(' + bg + ')',
'background-position': 'center',
'background-size': 'cover',
});
});
});
});
} else {
// Pure JS way
// alert("JS");
(function() {
window.addEventListener('load', wlImageLoader);
window.addEventListener('resize', wlImageLoader);
function wlImageLoader() {
console.log('event! Trig trig');
var all = document.getElementsByTagName("div");
var products = [];
for (i = 0; i < all.length; i++) {
if (all[i].hasAttribute('data-product-image')) {
products.push(all[i]);
}
}
Array.prototype.forEach.call(products, function(value) {
var bg = null;
var curent = window.getComputedStyle(value).getPropertyValue('background-image');
console.log(curent);
if (window.outerWidth < 500 || curent != 'none') return;
if (window.outerWidth < 1000 && curent == 'none') bg = value.getAttribute('data-product-image-s');
if (window.outerWidth >= 1000 && curent == 'none') bg = value.getAttribute('data-product-image');
// if (window.outerWidth >= 2000 && curent == null) bg = value.getAttribute('data-product-image-l');
if(bg == null || curent != 'none') return;
value.style.backgroundImage = "url(" + bg + ")";
value.style.backgroundPosition = "center";
value.style.backgroundSize = "cover";
curent = window.getComputedStyle(value).getPropertyValue('background-image');
console.log(curent);
});
}
})();
}
HTML
<div data-product-image="img/something_normal.jpg" data-product-image-s="img/something_small.jpg" id="p3" class="product">
However if you are a time loading freak you probably prefer to write your code natively in JS as you often don't use most of the jQuery library. For fast internet connection this is not a problem but if you target mobile devices on country side that might make a difference.
I would suggest combining perhaps the #import and #media commands to only #import the stylesheet which contains images if the #media tag meets you criteria (say, over a certain resolution).
So by default you wouldn't import the stylesheet which applies the BG image, you'd only end up doing it if you had determined the site was 'non-mobile'..if that makes sense!
The W3c site has some decent examples of combining the rules:
http://www.w3.org/TR/css3-mediaqueries/#media0
I want to disable a CSS class when the page loads. I have the class .rtsULmenuLeft:
.rtsULmenuLeft
{
list-style:none;
margin: 0;
padding: 0;
}
All instances of the style need to be disabled. How can I do this?
In ListStyle Image iam using custom image. It is displaying and again hidden at last. That is, with bullet marks it is displaying again. I need to have that custom image to be present. Thanks.
Here is a working example of what you have requested: http://jsfiddle.net/ALLew/
In the example:
all ULs are yelow
items with class rtsULmenuLeft are red
items with class rtsULmenuRight are blue
As you can see, the rtsULmenuLeft classNames are removed, and the lists are displayed yellow.
// Define a function to run on page load.
var loadCheck = function() {
// Cancel the function if the page isn't loaded...
if(document.readyState !== "complete") {
// ... but call it again in 100 milliseconds.
setTimeout(loadCheck, 100);
return;
}
// From here on, the page is loaded.
// Obtain a list of all elements with the particular class name
var elList = document.getElementsByClassName("rtsULmenuLeft");
// Loop over the elements until there are no longer any with the class.
while(elList.length > 0) {
// For each element, remove the class.
elList[0].className = elList[0].className.replace(
/\brtsULmenuLeft\b/, // RegExp of class name in word boundaries
"" // Replace with empty string - remove it.
);
}
};
loadCheck();
Using jquery:
$('.rtsULmenuLeft').removeClass('rtsULmenuLeft');
Add display:none
.rtsULmenuLeft
{
list-style:none;
margin: 0;
padding: 0;
display:none
}
I have tried google, but I can not definite answer.
I am trying to edit the styles of #sidebar:hover from mootools. My css is as follows:
#hoverzone:hover {
background: #EEE;
}
Now, I am trying to edit the background color from mootools when the page loads, to signify javascript is enabled. I know I can do:
$('hoverzone').addEvent('mouseenter', function(){
this.setStyle('background','000');
});
But I was wondering if there is a function I could call at the load of the page, that does this in one line with out the user doing anything.
Thanks
Edit: Yes, I was rushing, and anciently typed over instead of mouseenter
you cannot target a pseudo selector with javascript. so you need to create a new CSS rule that overrides the old one.
http://jsfiddle.net/dimitar/Z9RPP/
var StyleWriter = new Class({
// css classes on the fly, based on by Aaaron Newton's old work
createStyle: function(css, id) {
try {
if (document.id(id) && id) return;
var style = new Element('style', {id: id||'',type:'text/css'}).inject(document.getElements('head')[0]);
if (Browser.ie)
style.styleSheet.cssText = css;
else
style.set('text', css);
} catch(e) {
//console.log("failed:", e);
}
}
});
new StyleWriter().createStyle("#hoverzone:hover { background:red;}", "foo");
You can use the events domready or load of the windows object.
For example something like:
window.addEvent('load', function(){
$('hoverzone').setStyle('background-color','000');
});
Why use javascript. Why not just css:
#hoverzone { background: #000 }
#hoverzone:hover { background: #EEE }