Javascript assigned CSS background-image issue - javascript

I wrote this code that gives for each class .hpCarousel the relating background image.
The image names being: 0bg.jpg, 1jpg.bg, 2bg.jpg, etc...
for (i=0; i < 8; i++) {
$('.hpCarousel:eq('+i+')').css('background-image', 'url(wp-content/themes/blankslate/assets/carousel/'+i+'bg.jpg');
}
It works fine in Firefox. The classes have a style with their correct background-image assigned.
It does not work in Chrome OSX&WIN /Safari OSX/ IE. The .hpCarousel class divs have no style.
I thought at first it was something to do with Chrome's background refresh bug. But finding it on other browsers has made me think otherwise.
Am I clearly doing something wrong?
These classes are hidden on load. Does that make any difference? Then they fade in and out after one another to produce a carousel

Do you have errors in FireBug?
You could use another (more general) selector in the loop:
$('.hpCarousel:nth-child(' + i + ')')
Also the $.each iterator is a more convenient way to iterate through your backgrounds.
$('.hpCarousel').each(function(index) {
$(this).css('background-image', 'url(wp-content/themes/blankslate/assets/carousel/'+index+'bg.jpg');
});

Related

Flexslider breaks jQuery accordion [duplicate]

I have a test page to better explain my problem. I have several items on a list (they're images on the test page); when I click on one of them, a corresponding slideshow, using flexslider, sldes down.
The problem is that, on page load, the slideshow shows all slides at once, at a much smaller size than intended. But then, if I switch the focus from the window (i.e. switch between browser tabs or move to another program and come back), the slideshow is now working and the slides are the proper size. This happens in mobile devices too.
When I check with firebug, there's an element.style rule applying to ul.slides:
transform: translate3d(-89px, 0px, 0px);
Which hides one of the slides. Additionally, there's another rule for the list items inside ul.slides that gives them their initial width, which is not even the same for all sliders so I don't understand where it is coming from.
Can someone take a look and suggest a fix? I've tried overriding the element.style rule but so far unsuccessfully.
I think I've figured it out, in principal at least...
.flexslider{display:none;} seems throw off the re-size function of Flexslider.
You could just remove it, but that makes for some ugly loading.
To avoid said ugly loading I put together a quick, work-around- jsFiddle
$(document).ready(function(){
$(".flexslider").css('display','block').slideUp();
});
There's a still a quick glitch while loading, but hopefully it will at least steer you in the right direction.
Another method I played with a bit was to try and force the re-size function like so-
$(".client").click(function () {
$('.flexslider').resize(); // Problematic but promising
var project = this.id;
var project_id = '#' + project + '-project';
var elem = $(".flexslider:visible").length ? $(".flexslider:visible"): $(".flexslider:first");
elem.slideUp('slow', function () {
$(project_id).slideDown('slow');
});
});
This sort of solved the mini-picture issue, but was spotty at best.

Unable to set CSS background-image property with JavaScript

Edit:
For whatever reason, this does not work with JavaScript. It won't let you set the background image multiple times. To fix this, I set the backgroundPosition property to calc(50% + translation_x) calc(50% + translation_y) instead of setting a transformation in the image. This seems to work (for now).
I am unable to set the "background-image" property of an element dynamically with JavaScript. I have had no issues doing so in the past, but my current script does not work at all. There are no error messages in the console, so I haven't the slightest idea what's happening.
I have created vector graphics for a game and I am attempting to move them across the screen using a group (<g transform = "translate(x, y)">). My script takes the current background of the element, background.style.backgroundImage, and replaces the line containing the group with the transformed version.
Now, if I run
background.style.backgroundImage = "url(\"" + transformed_background + "\")";
console.log(background.style.backgroundImage);
the old version of the background image (without transformations) is (predictably) displayed in the output and the image does not update. For instance, the output might be
… <svg xmlns=\'http://www.w3.org/2000/svg\' width=\'5000\' height=\'5000\'><g> …
while the output of
console.log(transformed_background);
is correct, and is something to the effect of
… <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"5000\" height=\"5000\"><g transform="translate(1327.0717423133253, 1819.0229885057504)"> …
The background of the element will not change, despite my best efforts. I have tried everything imaginable in an attempt to resolve this issue. I believed it might be caused by the loop it is in (with an interval of about 50 ms), but increasing the interval had no effect. This system works elsewhere in the script (where the background is set initially), and this segment uses the same method.
The script is available here, and the issue is on line 175.
Any information would be much appreciated.
Thanks!
The only thing I see is at line 177,
where you use the var from line 175.
You wrote there
document.getElementById("background").backgroundImage = "url(\"" + build_background + ")";
But if I am not wrong you change the background with js like that.
document.getElementById("background").style.backgroundImage = "url(\"" + build_background + ")";
So you forgot the style.
Btw why do you write the js in the html window and not in the window for js?

How can I ensure this CSS transition animates

I have an image carousel built using knockout & jquery.
To animate the slides I really want to use CSS transitions and NOT jquery animate.
I have this nearly working but I have an issue.
In the code below, the 'slideRight' part doesn't work, however the else part works fine. What's happening is the transition to margin-left 0 is being skipped, even though the transition class has been added.
if (slideRight) {
$(requestedElement).insertBefore(currentElement);
slideContainer.css('margin-left', -$(self.carousel).width());
slideContainer.addClass('transition');
slideContainer.css('margin-left', 0);
} else {
$(requestedElement).insertAfter(currentElement);
slideContainer.addClass('transition');
slideContainer.css('margin-left', -$(self.carousel).width());
}
I've created a JSFiddle here: http://jsfiddle.net/vnw57nx0/2/
As you'll see in the fiddle, the carousel transitions nicely between slides going right to left.
But if you find this line in the javascript:
self.setIndex(self.currentIndex() + 1);
and change it to:
self.setIndex(self.currentIndex() - 1);
the slides should cycle in reverse.
They do, but they're not being animated.
Interestingly, if I debug the script and step through it works fine.
This made me think it was a timing issue and maybe I need to use a callback function but jquery .insertBefore, .css and .addClass are all synchronous.
Any ideas how I can fix this code that works if I debug but doesn't if I don't?
It seems that the browser doesn't make a transition when you revert a style value within the same context. You need to do it in a new context using something like setTimeout:
if (slideRight) {
$(requestedElement).insertBefore(currentElement);
slideContainer.css('margin-left', -$(self.carousel).width());
setTimeout(function() {
slideContainer.addClass('transition');
slideContainer.css('margin-left', 0);
});
} else {
http://jsfiddle.net/vnw57nx0/3/
I found this question because of the Knockout tag, and although you've got Knockout references in your question, the problem has nothing to do with Knockout. In fact, your code is very anti-Knockout since you're using jQuery selectors within your "view model" and using observables where none are needed or even useful.

jQueryui animation with inital undefined height

See the following fiddle:
[edit: updated fiddle => http://jsfiddle.net/NYZf8/5/ ]
http://jsfiddle.net/NYZf8/1/ (view in different screen sizes, so that ideally the image fits inside the %-width layouted div)
The image should start the animation from the position where it correctly appears after the animation is done.
I don't understand why the first call to setMargin() sets a negative margin even though the logged height for container div and img are the very same ones, that after the jqueryui show() call set the image where I would want it (from the start on). My guess is that somehow the image height is 0/undefined after all, even though it logs fine :?
js:
console.log('img: ' + $('img').height());
console.log('div: ' + $('div').height());
$('img').show('blind', 1500, setMargin);
function setMargin() {
var marginTop =
( $('img').closest('div').height() - $('img').height() ) / 2;
console.log('marginTop: ' + marginTop);
$('img').css('marginTop', marginTop + 'px');
}
setMargin();
Interesting problem...after playing around with your code for a while (latest update), I saw that the blind animation was not actually firing in my browser (I'm testing on Chrome, and maybe it was firing but I wasn't seeing it as the image was never hidden in the first place), so I tried moving it inside the binded load function:
$('img').bind('load', function() {
...
$(this).show('blind', 500);
});
Now that it was animating, it seemed to 'snap' or 'jump' after the animation was complete, and also seemed to appear with an incorrect margin. This smacks of jQuery not being able to correctly calculate the dimensions of something that hadn't been displayed on the screen yet. On top of that, blind seems to need more explicit dimensions to operate correctly. So therein lies the problem: how to calculate elements' rendered dimensions before they've actually appeared on the screen?
One way to do this is to fade in the element whose dimensions you're trying to calculate very slightly - not enough to see yet - do some calculations, then hide it again and prep it for the appearance animation. You can achieve this with jQuery using the fadeTo function:
$('img').bind('load', function() {
$(this).fadeTo(0, 0.01, function() {
// do calculations...
}
}
You would need to work out dimensions, apply them with the css() function, blind the image in and then reset the image styles back to their original states, all thanks to a blind animation that needs these dimensions explicitly. I would also recommend using classes in the css to help you manage things a little better. Here's a detailed working example: jsfiddle working example
Not the most elegant way of doing things, but it's a start. There are a lot more easier ways to achieve seemingly better results, and I guess I just want to know why you're looking to do image blinds and explicit alignment this way? It's just a lot more challenging achieving it with the code you used...anyways, hope this helps! :)

jQuery animate problems

I use the following snippet to make an element's background lightblue, then slowly fade to whiite over 30 seconds:
$("#" + post.Id).css("background-color", "lightblue")
.animate({ backgroundColor: "white" }, 30000);
Two questions.
First, instead of fading to white, is there a way to fade opacity to 100%? That way I don't have to change "white" if I choose to change the page's background color?
Second, about once out of every 10 or 15 times, the background stays lightblue and fails to fade to white. I'm using the latest versions of jQuery and the UI core. What could be going wrong?
EDIT: Bounty is for a solution to problem regarding second question.
EDIT2:
Apparently I got downvoted into oblivion because I said I rolled my own solution but didn't show it. My bad. I didn't want to be self-promoting. My code works 100% of the time and doesn't require jQuery. A demonstration and the code can be found at:
http://prettycode.org/2009/07/30/fade-background-color-in-javascript/
For your second question: in my experience this is usually because a Javascript error has occurred somewhere else on the page. Once there is one Javascript exception, the rest of the page stops running Javascript. Try installing Firebug (if you haven't already), then open up the "Console" tab and enable it. Then any javascript errors or exceptions will be printed to the console.
Another thing to try (which kinda contradicts my last statement...) is to disable all your browser plug-ins to see if you can recreate. Sometimes they interfere with scripts on the page (particularly GreaseMonkey.)
If you could provide a sample HTML snippet which reproduces this animation problem it would be a lot easier for us to help you. In the script I have pasted below, I can click it all day, as fast or slow as I like, and it never fails to animate for me.
For the first question: I know you said you'd found a workaround, but the following works for me (even on IE6) so I thought I'd post it, since it may be different from what you were thinking. (Note that setting CSS "opacity" property through jQuery.css() works on IE, whereas IE does not support the "opacity" property directly in CSS.)
<html>
<head>
<style>
body { background-color: #08f; }
#test { background-color: white; width: 100px; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
var myOpacity = 0.125;
$(function(){
$('#test').css('opacity', myOpacity);
$('a').click(function(){
myOpacity = 1.0 - myOpacity;
$('#test').animate({ opacity: myOpacity });
return false;
});
});
</script>
</head>
<body>
<p>Click me</p>
<div id="test">Test</div>
</body></html>
Dont forget the color plugin.
See here
When the color fails to animate to blue you could try to use the callback function to log a message to the console. You can then check that the event actually fired and completed. If it does then you could potentially use two animates. The first one to animate to a halfway house color then the use the callback to animate to white (so you get two bites of the cherry, if the outer fails but completes the callback has a second go)
It would be good if you could try to recreate the issue or give a url of the issue itself.
e.g
$("#" + post.Id).css("background-color", "lightblue")
.animate({ backgroundColor: "#C0D9D9" }, 15000, function(){
$(this).animate({ backgroundColor: "#ffffff" }, 15000)
});
You could always use something like this, avoiding the JQuery animate method entirely.
setTimeout(function() { UpdateBackgroundColor(); }, 10);
UpdateBackgroundColor() {
// Get the element.
// Check it's current background color.
// Move it one step closer to desired goal.
if (!done) {
setTimeout(UpdateBackgroundColor, 10);
}
}
Also, you may be able to remove the "white" coding by reading the background color from the appropriate item (which may involve walking up the tree).
It is possible to have jQuery change the Opacity CSS property of an item (as mentioned in another answer), but there's two reasons why that wouldn't work for your scenario. Firstly, making something "100% opaque" is fully visible. If the item didn't have any other modifications to its opacity, the default opacity is 100%, and there would be no change, so I'm guessing you meant fading to 0% opacity, which would be disappearing. This would get rid of the light blue background, but also the text on top of it, which I don't think was your intent.
A potentially easy fix for your situation is to change the color word "white" to "transparent" in your original code listing. The color plugin may not recognize that color word (haven't checked documentation on that yet), but setting the background color to "transparent" will let whatever color behind it (page background, if nothing else) shine through, and will self-update if you change your page background.
I'll answer your first question.
You can animate opacity like this:
.animate({opacity: 1.0}, 3000)
I think you can try using fadeOut/fadeIn too..
What about:
$("#" + post.Id).fadeIn( "slow" );
You could possibly have two divs that occupy the same space (using position: absolute; and position: relative; setting the z-index on one higher to make sure one is above and the other is below. the top one would have a transparent background and the one below would have a background color. then just fadeout the one below.
As for the second question:
If you think the default animation classes from JQuery are not properly working you could try Bernie's Better Animation Class. I have some good experiences with that library.
Animate only works for numbers. See the jquery docs. You can do opacity but you can't do background color. You can use the color plug in. Background-color uses strings like 'red', 'blue', '#493054' etc... which are not numbers.

Categories