jQuery - Get length and trigger click in increments based on length - javascript

Sorry if I'm completely missing with the title, I'm not entirely sure how to word what it is I'm trying to achieve. Any help would be great!!
Over the past few months in my free time I've been setting myself tasks to help myself understand and learn javascript / jQuery. So far all is going well but I've hit a bit of a bump in the road!
Essentially what I've created is a pretty simple set of tabbed content with a changing banner. When you click a tab, the relevant banner fades in and the previous banner fades out
Here's a fiddle: http://jsfiddle.net/unn9s4yf/
So what I'd like to do and where I'm kind of stuck is I'd like the banners to automatically "rotate", by fading in and out in the tabbed order every 10 seconds or so.
So kind of like a trigger click, but I feel as if that'd be the wrong way to go?
$('.thumb' + idAttr).trigger("click");
With a timeout attached? I'm not sure? I'm also not sure how to increment it each time so if this was the chosen method, how would it start at thumb 1, then click 2, 3, 4 & so on?
I've got the number of thumbs inside the div using
var thumbCount = $('#thumbs a').length;
Which returns 15 which is correct. So I guess it'd be something like when idAttr = .length start over from 1 again?
I'd also like to be able to pause the "auto click" function when I hover overthe main banner or thumbnails, I don't know if this is achievable though?
I know I'm asking a lot here.... At least I think I am. But any help or guidance on any part of this would be massively appreciated.
Thank you for your time!

I forked your jsfiddle and tried to do what you asked.
http://jsfiddle.net/OxyDesign/2g5Lav12/
It changes every 3 seconds, comes back to first thumb after the last thumb, stops on mouseenter & plays on mouseleave (on thumbs & banners), and stops on click & plays on second click on the same thumb.
HTML
<div id="container">
<div id="thumbs">
<a class="thumb active"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
<a class="thumb"></a>
</div>
<div id="banner">
<div class="banner active"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
<div class="banner"></div>
</div>
</div>
CSS
#container {width: 960px; margin: 0 auto;}
div,
a {float: left; display: block;}
#thumbs {width: 600px;}
.thumb {width: 110px; height: 156px; margin: 0 10px 10px 0; cursor: pointer;}
.thumb:hover,
.thumb.active,
.thumb.clicked {opacity: 0.5;}
.thumb:nth-child(even) {background: #ccee44;}
.thumb:nth-child(odd) {background: #ff33dd;}
#banner {width: 360px;}
.banner {width: 360px; height: 488px; position: absolute; display: none;}
.banner.active {display: block;}
.banner:nth-child(even) {background: #ccee44;}
.banner:nth-child(odd) {background: #ff33dd;}
JS
$(document).ready(function() {
var thumbs = $('.thumb'),
firstThumb = thumbs.eq(0),
banners = $('.banner'),
all = thumbs.add(banners),
duration = 3000,
rotating = false,
intervalRotate;
function setAutoRotate(){
intervalRotate = setInterval(autoRotate,duration);
rotating = true;
}
function stopAutoRotate(){
clearInterval(intervalRotate);
rotating = false;
}
function autoRotate(){
var nextThumb = thumbs.filter('.active').next();
if(!nextThumb.length) nextThumb = firstThumb;
rotate(nextThumb);
}
function rotate(activeThumb){
thumbs.removeClass('active');
activeThumb.addClass('active');
banners.removeClass('active').eq(thumbs.index(activeThumb)).addClass('active');
}
thumbs.on('click',function(e){
e.preventDefault();
var thumb = $(this);
if(thumb.hasClass('clicked')){
thumb.removeClass('clicked');
}else{
stopAutoRotate();
thumbs.removeClass('clicked');
thumb.addClass('clicked');
rotate(thumb);
}
});
all.on('mouseenter',function(){
if(rotating) stopAutoRotate();
});
all.on('mouseleave',function(){
if(!thumbs.filter('.clicked').length) setAutoRotate();
});
setAutoRotate();
});
Is it the behaviour you wanted ?

Triggering a click with a timeout should work fine. You could even do it recursively if you never want it to end. Also, you can set a variable to decide when to stop the rotation
$(function() {
$('.thumb').click(function(event, isAutoClick){
//Is Not automatic click, set false
if (!isAutoClick) isRotationActive = false;
//Other Click Code
});
//If hover over banner, stop rotation
$("#banner").on("mouseover", function() {
isRotationActive = false;
});
rotate($(".thumb"), 0);
});
var isRotationActive = true;
function rotate($clickables, currentIndex) {
//Make sure currentIndex is valid
currentIndex = currentIndex % $clickables.length;
//Trigger current click
$clickables.eq(currentIndex).trigger("click", [true]); //Passes [true] for isAutoClick
//Call again in 1 second with the next index
setTimeout(function() {
isRotationActive && rotate($clickables, currentIndex + 1)
}, 1000);
}
Updated Fiddle here: http://jsfiddle.net/unn9s4yf/3/

An Additional Solution:
var thumbs = $('.thumb');
var currentThumb = 0;
var changingStopped = false;
var changeBanner = function() {
console.log(thumbs.eq(currentThumb));
thumbs.eq(currentThumb).click();
currentThumb >= thumbCount - 1 ? currentThumb = 0 : currentThumb++;
setTimeout(function() {
checkIfChange();
}, 1000);
}
// triggers 'changeBanner()' if the user isn't currently stopping it.
var checkIfChange = function() {
if (!changingStopped)
{
changeBanner();
}
}
// makes the rotation stop
$('.thumb').mouseenter(function() {
changingStopped = true;
$(this).trigger('click'); // Assuming you want the hovered-over thumb to be displayed in the banner.
currentThumb = $(this).index() + 1; // Additional Option to make the rotation begin again from the current thumb.
});
// makes the rotation start again
$('.thumb').mouseleave(function() {
changingStopped = false;
checkIfChange();
});
checkIfChange();
See JSFiddle. Cheers!

Related

Make Gif file play when user scrolls over and and stop afterwards

I found this while browsing and this plays and stops gifts on hover:
http://docs.embed.ly/docs/tutorial-play-and-stop-gifs
I would like to maintain this functionality but by playing only once, when user scrolls over that section. I believe jQuery waypoints can be combined with this to achieve this, but my JS expertise fails to combine the two.
jQuery Waypoints
https://github.com/imakewebthings/waypoints
I believe an example HTML structure for this to start out would be something like this:
<div class="gifs row small-up-4">
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
<div class="column"> </div>
</div>
.gifs a {
position: relative;
display: block;
}
.gif-preload {
display: none;
}
.gif-loading {
position: absolute;
width: 40px;
height: 40px;
font-size: 40px;
color: #fff;
top: 0;
left: 0;
}
$.embedly.defaults.key = '1d5c48f7edc34c54bdae4c37b681ea2b';
$('.gifs a').embedly({
display: function(obj) {
if (obj.type === 'photo') {
var $this = $(this);
// Create the static image src with Embedly Display.
var src = $.embedly.display.display(obj.url, {
query: {
animate: false
}
});
// Add static gif placeholder to the parent
$this.html('<img class="gif-holder" src="' + src + '" />');
// Start preloading the actually gif.
$this.append('<img class="gif-preload" src="' + obj.url + '" />');
// Create a promise so we can keep track of state.
$this.data('promise', $.Deferred());
// Get the element we added.
var elem = $this.find('.gif-preload').get(0);
// If the image is not in cache then onload will fire when it is.
elem.onload = function() {
$this.data('promise').resolve();
};
// If the image is already in the browsers cache call the handler.
if (elem.complete) {
$this.data('promise').resolve();
}
// Set the static gif url so we can use it later.
$(this).data('static_url', src);
} else {
// remove li if it's not an image.
$(this).parent().remove();
}
}
}).on('mouseenter', function() {
var $this = $(this);
// Set the hover state to true so that the load function knows to run.
$this.data('hover', true);
// Create a function to load the gif into the image.
var load = function() {
if ($this.data('hover') === true) {
// Remove the loading image if there is one
$this.find('.gif-loading').remove();
// Swap out the static src for the actually gif.
$this.find('img.gif-holder').attr('src', $this.data('embedly').url);
}
};
// Add the load function to the done callback. If it's already resolved
// this will fire immediately.
$this.data('promise').done(load);
// Add a spinner if it's not going to play right away.
if ($this.data('promise').state() === 'pending') {
// Add a loading spinner.
$this.append('<i class="gif-loading fa fa-spinner fa fa-spin"></i>');
// we need to center it over the image.
$this.find('.gif-loading').css({
top: $this.height() / 2 - 20,
left: $this.width() / 2 - 20
});
}
}).on('mouseleave', function() {
var $this = $(this);
// Make sure the load function knows we are no longer in a hover state.
$this.data('hover', false);
// Remove the spiner if it's there.
$this.find('.gif-loading').remove();
// Set the src to the static url.
$this.find('img.gif-holder').attr('src', $(this).data('static_url'));
});
This is not a perfect answer, but it will guide you a bit on how to implement.
Solution: everytime you scroll, check GIFS in screen an play them and stop those who aren't in screen.
1) everytime you scroll...
Simply using
$(document).scroll(onScroll);
onScroll function is gonna be called everytime you scroll.
2) check GIFS in screen an play them and stop those who aren't in screen
To know when a HTML element is in the screen, you can head to "Check if element is visible after scrolling" question.
So for example, based on this answer we could use:
/**
* Is element within visible region of a scrollable container
* #param {HTMLElement} el - element to test
* #returns {boolean} true if within visible region, otherwise false
*/
function isScrolledIntoView(el) {
var rect = el.getBoundingClientRect();
return (rect.top >= 0) && (rect.bottom <= window.innerHeight);
}
Final Solution
Combining your code, with the above, you can use this:
function isScrolledIntoView(el) {
var rect = el.getBoundingClientRect();
return (rect.top >= 0) && (rect.bottom <= window.innerHeight);
}
function animateGifsInScreen() {
$('.gifs a').each(function(index, el) {
if(isScrolledIntoView(el)) {
$(el).trigger('mouseenter');
} else {
$(el).trigger('mouseleave');
}
});
}
$(document).scroll(animateGifsInScreen);
What I'm doing: every time you scroll, I iterate over all gifs and play/stop them depending if they are on screen or not. For play/stop, I just trigger mouseenter/mouseleave respectively.
This may not be the ideal solution for your case but I'm pretty sure it will guide you to the correct answer.
There is a sample: https://jsfiddle.net/e8av59g2/ (it has a bug, you have to scroll at least once to made it work hehe).

After hovering on images at the top of a webpage I want to specific div and hide other div based on the image hover

First, all three line of text will visible. Those are in different div. When I hover on IMAGE 1, only the first div should visible and other two should be hidden.
Like this, If I hover on IMAGE 3, only the third div text or 3rd line should visible and other line should hide.
Can you please sugget me how to achive that? Or can you give me a working example or code please? I tried using different way but failed.
Please check the html code in jsfiddle.
https://jsfiddle.net/mdykabir/ex67pfs1/2/
<div class="images">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/1.png">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/2.png">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/3.png">
</div>
<div class="infoArea">
<div id="infOne">
Show this div if hover on image 1.
</div>
<div id="infTwo">
Show this div if hover on image 2.
</div>
<div id="infThree">
Show this div if hover on image 3.
</div>
<div>
You add an event handler for mouseover/mouseout on the images, like this, and then toggle a class which hides/shows the div
window.addEventListener('load', function() {
var images = document.querySelectorAll('.images > img');
var divs = document.querySelectorAll('.infoArea > div');
for (i = 0; i < images.length; i++) {
(function(i){
images[i].addEventListener('mouseover', function(e) {
document.querySelector('.infoArea').classList.toggle('hide');
divs[i].classList.toggle('show');
})
images[i].addEventListener('mouseout', function(e) {
document.querySelector('.infoArea').classList.toggle('hide');
divs[i].classList.toggle('show');
})
})(i);
}
})
.infoArea.hide div {
display: none;
}
.infoArea > div.show {
display: block;
}
<div class="images">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/1.png">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/2.png">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/3.png">
</div>
<div class="infoArea">
<div id="infOne">
Show this div if hover on image 1.
</div>
<div id="infTwo">
Show this div if hover on image 2.
</div>
<div id="infThree">
Show this div if hover on image 3.
</div>
<div>
With a small markup change you don't even need script, just CSS hover
.images {
display: inline-block;
}
.images:hover ~ .infoArea > div {
display: none;
}
.images.imgOne:hover ~ .infoArea #infOne,
.images.imgTwo:hover ~ .infoArea #infTwo,
.images.imgThree:hover ~ .infoArea #infThree {
display: block;
}
<div class="images imgOne">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/1.png">
</div>
<div class="images imgTwo">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/2.png">
</div>
<div class="images imgThree">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/3.png">
</div>
<div class="infoArea">
<div id="infOne">
Show this div if hover on image 1.
</div>
<div id="infTwo">
Show this div if hover on image 2.
</div>
<div id="infThree">
Show this div if hover on image 3.
</div>
<div>
Based on a comment, here is a sample how to toggle on click, with persistent result
window.addEventListener('load', function() {
var images = document.querySelectorAll('.images > img');
var divs = document.querySelectorAll('.infoArea > div');
for (i = 0; i < images.length; i++) {
(function(i,old){
images[i].addEventListener('click', function(e) {
old = document.querySelector('.infoArea .show');
if (old) {
old.classList.toggle('show');
}
if (old != divs[i]) {
divs[i].classList.toggle('show');
}
})
})(i);
}
})
.infoArea div {
display: none;
}
.infoArea > div.show {
display: block;
}
<div class="images">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/1.png">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/2.png">
<img src="http://www.mykabir.info/wp-content/uploads/2017/01/3.png">
</div>
<div class="infoArea">
<div id="infOne">
Show this div if hover on image 1.
</div>
<div id="infTwo">
Show this div if hover on image 2.
</div>
<div id="infThree">
Show this div if hover on image 3.
</div>
<div>
You can use the mouseover and mouseout DOM events.
Here's a minimal example that accomplishes what you want with your example:
function showOnHover(args) {
var trigger = args.trigger;
var target = args.target;
trigger.addEventListener('mouseover', function(e) {
target.style.display = 'block';
})
trigger.addEventListener('mouseleave', function(e) {
target.style.display = 'none';
})
}
var images = document.querySelectorAll('.images img');
var toShow = document.querySelectorAll('.infoArea div');
var triggersAndTargets = Array.prototype.map.call(images, function (img, i) {
return { trigger: img, target: toShow[i] };
});
triggersAndTargets.forEach(showOnHover);
Try it here: https://jsfiddle.net/ex67pfs1/16/
And for an ES2015 version: https://jsfiddle.net/ex67pfs1/18/
Checkout this previous SO question for a jQuery solution.
This is how you do this in plain JS, I would stay away from CSS solutions if you target non sibling elements. If you target the element or a sibling, then do it with CSS, otherwise, there is now ay around JS.
This JS code can be done bit better, I will pack all into one function, but adding the listeners is a must.
var pic1 = document.getElementById('first');
var pic2 = document.getElementById('sec');
var pic3 = document.getElementById('thi');
pic1.addEventListener('mouseenter', function(){
var div1 = document.getElementById('infOne');
div1.style.opacity=1;
});
pic1.addEventListener('mouseout', function(){
var div1 = document.getElementById('infOne');
div1.style.opacity=0;
});
Check it out here, I changed some css as well.
https://jsfiddle.net/ex67pfs1/15/

Temporarily disable scroll at position/element with JS

I'm trying to find a way to lock the scroll at at a specified height or element for a certain amount of scrolls.
So in this plnkr I want it to stop on the second slide for 2-3 scrolls, and then proceed.
http://plnkr.co/edit/BAlFMLBhzVaqWuwhGCu8?p=preview
<div class="slide s1">S.O. made me include some code with plnkr link</div>
<div class="slide s2">Title 2</div>
<div class="slide s3">Title 3</div>
I've tried the following:
How to disable scrolling temporarily?
But if the user scrolls fast enough, they can scroll past the title.
I imagine this is because the UI thread is busy, and then when the JS finally kicks in, the title in the slide is out of view.
A good working example of what I'm looking for is here (on the second slide): http://journey.lifeofpimovie.com/
How does one achieve this effect?
I think link you have added is using some personal javascript plugins , it doesn't disable scrolling temporarily . I'm not familiar with these plugins but you can search for scrolling webpages plugins like this one : http://alvarotrigo.com/fullPage/
it has some Examples like this one and some others you can try .
Try
var $w = $(window);
var $slides = $('.slide');
$.fx.interval = -100;
var scrollTiles = function scrollTiles(e) {
var el = $slides.filter(function (i, el) {
return el.getBoundingClientRect().bottom >
parseInt($(el).css("height")) + 10
}),
// select second tile
tileId = el.prev().is($slides)
? el.prev().index()
: $slides.eq(-1).index();
// do stuff at second tile
if (tileId === 2) {
$slides.not(":eq(" + (tileId - 1) + ")")
.hide(0, function () {
$w.off("scroll.tiles");
$(this).queue("tiles", function () {
$(this).show(0)
})
// delay scroll three seconds
}).delay(3000)
.dequeue("tiles")
.promise()
.done(function (elems) {
// after three second delay ,
// scroll to third tile
$("body").animate({
scrollTop: elems.eq(-1).offset().top
}, 500, "linear", function () {
// prevent delay at second tile
// until after scroll to first tile from third tile ,
// reset `scroll.tiles` event
$w.on("scroll.t", function (e) {
if (elems.eq(0)[0].getBoundingClientRect().bottom >
elems.eq(0).height()) {
$(this).off("scroll.t")
.on("scroll.tiles", scrollTiles)
}
})
})
})
}
};
$w.on("scroll.tiles", scrollTiles);
/* Styles go here */
html,
body {
height: 100%;
}
.slide {
height: 100%;
}
.s1 {
background: red;
}
.s2 {
background: orange;
}
.s3 {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body>
<div class="slide s1">Title 1</div>
<div class="slide s2">Title 2</div>
<div class="slide s3">Title 3</div>
</body>

How to scroll back to the top of page on button click?

I am creating my product pages by using the object tag code, but every time I click the "view" button, the next page is staying at the same position of previous page which I just viewed. How can I add functionality that will let me view from the top of page every time I click the "view" button?
<div id="container" class="clearfix"><!--! end of #sidebar -->
<div class="holder"></div>
<div id="content" class="defaults"><!-- navigation holder -->
<div id="title2">Office Section</div>
<!-- item container -->
<ul id="itemContainer">
<li>
<div id="product">
<div id="title">FuBangĀ®</div>
<div class="imageOuter" style="margin:0">
<a class="image" href="officesection010.html">
<span class="rollover" ></span>
<img class="imgborder" src="product/officesection/010.jpg" width="165" height="165" />
</a>
</div><br />
<div id="text">Sofa </div><br />
<div id="button">
View Details
</div>
</div>
</li>
</ul>
<br />
<div id="title2"></div>
<div class="holder"></div>
</div>
</div> <!--! end of #content -->
</div> <!--! end of #container -->
When I click the "View Details" button at a specific position "x" here: http://postimg.org/image/vgs0lwhtr/
The next page shows the same position "x", but I want it to jump to the top of page:
http://postimg.org/image/vn80e2lph/
Using Javascript:
document.body.scrollTop = document.documentElement.scrollTop = 0;
Using jQuery:
$(function() {
$('body').scrollTop(0);
});
jQuery(document).ready(function($){
$(window).scroll(function(){
if ($(this).scrollTop() > 50) {
$('#backToTop').fadeIn('slow');
} else {
$('#backToTop').fadeOut('slow');
}
});
$('#backToTop').click(function(){
$("html, body").animate({ scrollTop: 0 }, 500);
//$("html, body").scrollTop(0); //For without animation
return false;
});
});
please refere this, may this help
Sometimes placing scroll to body doesn't work if your current content is generated through jQuery (as it was in my case). In such situation you can just do following.
$(function() {
$('html').scrollTop(0);
});
A small issue with Subhash's jQuery solution is that you must call this code within $(document).ready() in order for your $('body') selector to work. The ready event may not fire before parts of your page have been rendered to the screen.
An better approach is to simply modify the user's location as a work-around to this browser 'feature':
//Above all of your $(document).ready(...) code
document.location = "#";
Simple HTML solution for jumping between page parts
// Place a tag like this where you would like to go
// in your case at the top
<a name="top"></a>
// you will reach there by click of this link better use an image reach their by clicking on this we can also use an image, align in right
last
Back to top button, works in all browsers.To change the scroll speed simply change the x in counter -= x here x = 10
function scrollToTop(){
var myBody = document.body;
var id = setInterval(secondFunction,1);
var height = window.pageYOffset;
var counter = height;
function secondFunction(){
if(window.pageYOffset == 0){
clearInterval(id);
}
else {
if(!!navigator.userAgent.match(/Trident/g) || !!navigator.userAgent.match(/MSIE/g)){
counter -= 10;
counter--;
document.documentElement.scrollTop = counter;
}
else {
counter -= 10;
counter--;
myBody.scrollTop = counter;
}
}
}
}
body {
height: 5000px;
margin: 0;
padding: 0;
}
.backToTop {
position: fixed;
/* Fixed at page */
top: auto;
bottom: 20px;
left: auto;
right: 20px;
background-color: crimson;
color: white;
padding: 5px;
cursor: pointer;
}
header {
position: relative;
top: 0;
left: 0;
width: 100%;
height: 100px;
background-color: black;
}
<!-- back to top button -->
<span class="backToTop" onclick="scrollToTop()">TOP</span>
<!-- Header -->
<header>
</header>
Assign an id="#body" and tabindex in the <body> tag
<body id="#body" tabindex="1">
and use jquery focus()
$(function() {
$("#body").attr("tabindex",-1).focus();
}
You can use this method:
function gototop() {
if (window.scrollY>0) {
window.scrollTo(0,window.scrollY-20)
setTimeout("gototop()",10)
}
}

Rotate images, if last image then hide

I have 3 images that I want to rotate when a button is clicked.
image1, image2, image3.
If the image is at image1, then when clicked it should show image2 (and so on, in order of image1, .., image3).
When I am at image3, it should then hide the image, i.e. don't display it.
I need some help with the javascript function to do this, I already have the code for the button click event.
I am passing the toggle() function the jquery object $('myImageID');
$(document).ready(
function()
{
$('#button1').click( function() { toggleSector( $('#sector1') ) } ;
}
);
function toggleSector(o)
{
// help!
}
<div id="sector1"></div>
<input type="button" id="button1" value="Sector 1" />
Update
I have to somehow find the name of the current background image set to the
<div> where my image is.
Is there a background property to get the image name currently being displayed?
You can get a background-image by accessing it from the .css(name) method:
$("#sector1").css("background-image");
Without managing your list of images in an array or some other fashion, you're going to have to check each background-image to know when it's time to hide your element. This isn't a great way of working, as it doesn't allow you to easily add a new image in the future if you like.
Perhaps something like the following:
function toggle(el) {
var whenToHide = "background3.jpg";
var currBackground = $(el).css("background-image");
/* ...code... */
if (currBackground == whenToHide) {
$(el).remove();
}
}
Do you have to use the background image?
If not, here's a little code sample for what I would do.
<html>
<head>
<style type="text/css">
#imageRotater { list-style-type:none; }
#imageRotater, .imageRotater li { margin:0px auto; padding: 0px; }
#imageRotater img { display:none; }
</style>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"></script>
<script type="text/javascript">
(function($) {
$.fn.rotate = function() {
return this.each(function() {
var list = $(this).is('ul') ? $(this) : $('ul', this);
list.find('img:eq(0)').show();
$('img', list).click(function() {
$(this).hide().closest('li').next().find('img').show();
});
});
};
})(jQuery);
$(document).ready(function() {
$("#imageRotater").rotate();
});
</script>
</head>
<body>
<div id="sector1">
<ul id="imageRotater">
<li><img src="image1.png" alt="" /></li>
<li><img src="image2.png" alt="" /></li>
<li><img src="image3.png" alt="" /></li>
</ul>
</div>
</body>
</html>
Here's a thing that works.
Each overlay is initially hidden with CSS. Each time your button is clicked, all the overlays are hidden, then one is revealed based on some data stored on the button. If the data reaches the max number overlays + 1, none are shown and the data is reset to 0.
Markup
<div id="container" style="background: yellow">
<div class="overlay" style="background: red"></div>
<div class="overlay" style="background: green"></div>
<div class="overlay" style="background: blue"></div>
</div>
Style
div{
width: 100px;
height: 100px;
}
.overlay{
position: absolute;
top: 0;
left: 0;
display: none;
}
#container{
position: relative;
}
Script
$(function() {
var b = $('#button1');
b.data('next', 0);
b.data('max', $('.overlay').size()+1 );
b.click( function( e ) {
var next = $(this).data('next');
var o = $('.overlay');
o.hide();
o.eq(next).show();
next = (next+1) % $(this).data('max');
$(this).data('next', next);
});
});
In response to Bendeway's answer above, you'll need to insert before
list.find('img:eq(0)').show();
the following line:
list.find('img').hide();
This will hide all the images before it starts rotating through them.

Categories

Resources