I have a small problem with a small jQuery script that my slide images. The script itself works very well, its purpose being to scroll through the images indeed "fade", a classic.
The problem is that if I want to use it for another block on the page, well it no longer works properly .. The problem is certainly located at the id, but can not make it work.
Here is the script:
function slider() { function animate_slider(){ $('.slider #'+shown).animate({ opacity:0 // fade out },1000); $('.slider #'+next_slide).animate({ opacity:1.0 // fade in },1000); //console.log(shown, next_slide); shown = next_slide; } function choose_next() { next_slide = (shown == sc)? 1:shown+1; animate_slider(); } $('.slider #1').css({opacity:1}); //show 1st image var shown = 1; var next_slide; var sc = $('.slider img').length; // total images var iv = setInterval(choose_next,3500); $('.slider_nav').hover(function(){ clearInterval(iv); // stop animation }, function() { iv = setInterval(choose_next,3500); // resume animation }); $('.slider_nav span').click(function(e){ var n = e.target.getAttribute('class'); //console.log(e.target.outerHTML, n); if (n=='prev') { next_slide = (shown == 1)? sc:shown-1; } else if(n=='next') { next_slide = (shown == sc)? 1:shown+1; } else { return; } animate_slider(); }); } window.onload = slider;
Any idea ? Thank you all :)
$('.slider')
will target all attributes with that class. If you have two code blocks this one piece of code will affect both... which is not what you want. You would be better off writing this as a jQuery plugin where the element is the one you choose in the jQuery selector the plugin targets, not hard coded into your logic. – David Barker