Remove one image after another when onclick - javascript

i have a div that contains 5 of the same image. i'm trying to make a button that can make one of the images disappear one after another when onclick. i've tried the style.visibility but it makes them all disappear together. This is my code
document.getElementById("btn1").onclick = function() {
document.getElementById("output").style.visibility = "hidden";
}
<input id="btn1" type="button" value="Click me" onclick="onClick1()" style="height: 100px; width: 100px;">
<div style="margin-top: 40px;"></div>
<div id="output">
<img src="/images/person1.jpg">
<img src="/images/person1.jpg">
<img src="/images/person1.jpg">
<img src="/images/person1.jpg">
<img src="/images/person1.jpg">
</div>

You are targeting the image container and then hiding it so all the images disappear at once.
It's not really clear from your question whether you want to click the button once and have the images disappear, or to click the button repeatedly and have one image disappear on each click. This solution answers the first problem.
If you want to hide the images one-by-one you're going to need to use setInterval or setTimeout to manage that. In this example I've used setTimeout.
document.getElementById('btn1').onclick = function() {
// Get all the images
const images = Array.from(document.querySelectorAll('#output img'));
// Loop over the images
function loop(images) {
// If there are images left remove the first one,
// hide it, and then call the function again with the
// reduced image array until all images are gone.
if (images.length) {
const image = images.shift();
image.style.visibility = 'hidden';
setTimeout(loop, 1000, images);
}
}
loop(images);
}
<input id="btn1" type="button" value="Click me" onclick="onClick1()" style="height: 100px; width: 100px;">
<div style="margin-top: 40px;"></div>
<div id="output">
<img src="https://dummyimage.com/30x30/000/fff">
<img src="https://dummyimage.com/30x30/000/fff">
<img src="https://dummyimage.com/30x30/000/fff">
<img src="https://dummyimage.com/30x30/000/fff">
<img src="https://dummyimage.com/30x30/000/fff">
<img src="https://dummyimage.com/30x30/000/fff">
</div>
Additional documentation
shift
setTimeout
Array.from
If you want to make the images disappear on each click, cache the images, and return a function that the listener calls when you click the button.
const button = document.getElementById('btn1')
button.addEventListener('click', handleClick(), false);
// Cache the image elements, and then return a new
// function to your listener that removes an image on each click
function handleClick() {
const images = Array.from(document.querySelectorAll('#output img'));
return function() {
if (images.length) {
const image = images.shift();
image.style.visibility = 'hidden';
}
}
}
<input id="btn1" type="button" value="Click me" style="height: 100px; width: 100px;">
<div style="margin-top: 40px;"></div>
<div id="output">
<img src="https://dummyimage.com/30x30/000/fff">
<img src="https://dummyimage.com/30x30/000/fff">
<img src="https://dummyimage.com/30x30/000/fff">
<img src="https://dummyimage.com/30x30/000/fff">
<img src="https://dummyimage.com/30x30/000/fff">
<img src="https://dummyimage.com/30x30/000/fff">
</div>

You should give id's to image tag instead of parent div.
Created variable which which will work as a counter.
On each click increase counter and hide the specific image tag.
Your code will look like:
let imageToDelete = 1;
document.getElementById("btn1").onclick = function() {
document.getElementById("image_" + imageToDelete).style.visibility = "hidden";
imageToDelete++;
}
<input id="btn1" type="button" value="Click me" onclick="onClick1()" style="height: 100px; width: 100px;">
<div style="margin-top: 40px;"></div>
<div>
<img id="image_1" src="/images/person1.jpg">
<img id="image_2" src="/images/person1.jpg">
<img id="image_3" src="/images/person1.jpg">
<img id="image_4" src="/images/person1.jpg">
<img id="image_5" src="/images/person1.jpg">
</div>

With that script, all you are doing is hiding the parent of all the images, which results in all the images "seemingly disappearing" at once. You have to remove each separately to achieve your desired result.
const RemoveImage = Event => {
const Target = Event.target;
const ImgPos = Target.getAttribute("data-remove");
const Selector = `#image-parent > img:${ImgPos}-of-type`;
const ImgToRemove = document.querySelector(Selector);
if(!ImgToRemove) return false;
ImgToRemove.parentElement.removeChild(ImgToRemove);
return true;
};
const Buttons = document.querySelectorAll("button[data-remove]");
Buttons.forEach(btn => btn.addEventListener("click", RemoveImage));
#image-parent > img:hover {
filter: brightness(92%);
}
#first {outline: 2px solid #a00;}
#last {outline: 2px solid #0a0;}
<div id="image-parent">
<img src="https://via.placeholder.com/70" id="first">
<img src="https://via.placeholder.com/70">
<img src="https://via.placeholder.com/70">
<img src="https://via.placeholder.com/70" id="last">
</div>
<button data-remove="first">Remove first img</button>
<button data-remove="last">Remove last img</button>
If you don't want the images to be removed fully, but rather just hidden:
Rreplce the line ImgToRemove.parentElement.removeChild(ImgToRemove); with something like ImgToRemove.classList.add("hidden-by-css");
Then declare this CSS class with opacity: 0; pointer-events: none;.

We know manipulating HTML DOM is not popular option. But this will work with your problem.
document.getElementById("btn1").onclick = function() {
let imageNode = document.getElementById("output").getElementsByTagName('img')[0];
imageNode.parentNode.removeChild(imageNode)
}

I have found that using the queue() and dequeue() methods from jQuery library is a very good option for resolving this step by step scenarios. This is the stated description of this in the official page:
"Queues allow a sequence of actions to be called on an element asynchronously, without halting program execution. "
I will leave an brief example of how I have implemented it in the past:
$('#anchoredToElement')
.queue("steps", function (next) {
console.log("Step 1");
//In case you want to hold the execution for a bit depending on the scenario you're running
setTimeout(function () { console.log("Action within timeout") }, 500);
next();
})
.queue("steps", function (next) {
console.log("Step 2");
setTimeout(function () {
//Execution example
UploadFile(fileUpload))
}, 500);
next();
})
.dequeue("steps");
Here an example of how I think the logic could be for your needs:
var removeImage = function (index) {
//Logic here to remove image within div according to passed index
};
var index = 0;
$('#output')
.queue("steps", function (next) {
console.log("Remove Image 1");
setTimeout(function () { removeImage(index); }, 250);
index++;
next();
})
.queue("steps", function (next) {
console.log("Remove Image 2");
setTimeout(function () { removeImage(index); }, 250);
index++;
next();
})
.queue("steps", function (next) {
console.log("Remove Image 3");
setTimeout(function () { removeImage(index); }, 250);
index++;
next();
})
.queue("steps", function (next) {
console.log("Remove Image 4");
setTimeout(function () { removeImage(index); }, 250);
index++;
next();
})
.queue("steps", function (next) {
console.log("Remove Image 5");
setTimeout(function () { removeImage(index); }, 250);
index++;
next();
})
.dequeue("steps");
Of course you can improve the JS code as I was just focusing on the step by step process.
This is just a first glance of how $.queue can help you to achieve the step by step process. I recommend to go check the documentation to learn the details and so apply it to your logic as needed.

Related

Displaying an image after clicking 100 times on a button

I'm new here and I still have some difficulties in coding.
I'm trying to create an html page for some friends and I managed to create a click counter, an image which appear and disapear after some time etc
However the only thing that I can't manage to do is how I can make an image appear after clicking on the button for 100 or 1000 times. I can make the image appear after clicking on the button one time, but I don't know how to make it appear only after some clicking.
If someone can help me I'll be very glad!
$button = document.querySelector('button')
$span = document.querySelector('span')
function increment() {
$span.innerHTML++;
}
$button.addEventListener('click', increment);
document.addEventListener("DOMContentLoaded", function() {
setTimeout(function() {
showImage();
setInterval(hideImage, 8000);
}, 5000);
});
function hideImage() {
document.getElementById("imgHideShow").style.display = "none";
}
function showImage() {
document.getElementById("imgHideShow").style.display = "block";
}
<img class="prayme" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Tram_icon_black_and_transparent_background.svg/1024px-Tram_icon_black_and_transparent_background.svg.png">
<p>You prayed <span id='count'>0</span> times</p>
<div id="image">
<img src="https://pbs.twimg.com/profile_images/998926585691451392/WlkEVV7x_400x400.jpg">
</div>
<div class="text-center">
<button><img class="imgbutton" src="https://www.nicepng.com/png/detail/980-9803933_emoji-emoji-pray-thankyou-thanks-praying-hands-emoji.png">
Afficher l'image
</button>
</div>
<div>
<img src="https://i.stack.imgur.com/1dpmw.gif" class="browse-tip" id="imgHideShow">
</div>
You just need to add an if statement, checking if the innerHTML is more or equal to 100, and then call showImage().
I removed code that wasn't relevant.
I added declarations to the variables by adding let in front the name.
I removed the button, and put an event listener directly on the image instead.
I think the rest of the code is self-explanatory.
let spanElement = document.querySelector('span');
let imgButton = document.getElementById('imgbutton');
function increment() {
spanElement.innerHTML++;
if (spanElement.innerHTML >= 5) {
showImage();
}
}
imgButton.addEventListener('click', increment);
document.addEventListener("DOMContentLoaded", function() {
setInterval(hideImage, 8000);
});
function hideImage() {
document.getElementById("imgHideShow").style.display = "none";
}
function showImage() {
document.getElementById("imgHideShow").style.display = "block";
}
img {
height: 3rem;
}
#imgHideShow.hidden {
display: none;
}
<img class="prayme" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Tram_icon_black_and_transparent_background.svg/1024px-Tram_icon_black_and_transparent_background.svg.png">
<p>You prayed <span id='count'>0</span> times</p>
<div class="text-center">
<img id="imgbutton" src="https://www.nicepng.com/png/detail/980-9803933_emoji-emoji-pray-thankyou-thanks-praying-hands-emoji.png">
Afficher l'image
</div>
<div>
<img src="https://i.stack.imgur.com/1dpmw.gif" class="hidden browse-tip" id="imgHideShow">
</div>
To make the code even more readable, I would also add the following it it like this:
Add a constant for how many times the user need to click.
Declare variables for all the elements that are affected.
Use a class (.hidden) to hide the image, and add/remove that class, instead of adding a style. You should only add a style if you can't toggle classes.
const TARGET_TO_SHOW_IMAGE = 5;
let spanElement = document.querySelector('span');
let imgButton = document.getElementById('imgbutton');
let imgHideShow = document.getElementById("imgHideShow");
let numberOfTimesClicked = 0;
function increment() {
numberOfTimesClicked++;
if (numberOfTimesClicked >= TARGET_TO_SHOW_IMAGE) {
showImage();
numberOfTimesClicked = 0; // resets
}
spanElement.innerHTML = numberOfTimesClicked;
}
imgButton.addEventListener('click', increment);
document.addEventListener("DOMContentLoaded", function() {
setInterval(hideImage, 8000);
});
function hideImage() {
imgHideShow.classList.add('hidden');
}
function showImage() {
imgHideShow.classList.remove('hidden');
}
img {
height: 3rem;
}
#imgHideShow.hidden {
display: none;
}
<img class="prayme" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Tram_icon_black_and_transparent_background.svg/1024px-Tram_icon_black_and_transparent_background.svg.png">
<p>You prayed <span id='count'>0</span> times</p>
<div class="text-center">
<img id="imgbutton" src="https://www.nicepng.com/png/detail/980-9803933_emoji-emoji-pray-thankyou-thanks-praying-hands-emoji.png">
Afficher l'image
</div>
<div>
<img src="https://i.stack.imgur.com/1dpmw.gif" class="hidden browse-tip" id="imgHideShow">
</div>

Loop a click event function on "animationend"

I have a question on how to loop a click event itself on animation end
I have 3 pictures i want to rotate on click with an order :
first click on first picture-> first picture rotates,
second click on second picture-> second picture rotates,
third click on third picture-> third picture rotates
the add event listener is the same so i'm trying to loop the function on itself with myEndFunction() but it seems to not be alright
On second click the second picture is moving but i still have to click on first picture
here is the html (very classic one):
<body>
<img id ="first" src= "https://i.ibb.co/bPWLLjV/bookermini.png" alt="booker">
<img id ="second" src= "https://i.ibb.co/KKKqrBp/bobafettmini.png" alt="boba">
<img id ="third" src= "https://i.ibb.co/2yXfmvJ/hommemini.png" alt="joxer">
</body>
here is the css (moving part):
.move {
position : relative;
animation: mymove 1s ;
}
#keyframes mymove {
100%{transform: rotate(360deg); }
}
here is the js code :
var x = document.getElementById("first");
x.addEventListener('click', event => {
x.classList.add("move");
x.addEventListener("webkitAnimationEnd", myEndFunction);
x.addEventListener("animationend", myEndFunction);
function myEndFunction() {
x = document.getElementById("second");
}
});
here is a codepen if you want to try : https://codepen.io/minise/pen/vYGpqJZ
plz i need your help !
It seem that you are using an #id selector which returns always the first occurrence, and stops.
My suggestion would be, to use class identifiers instead and reuse your action function.
var version1 = function () {
// get all containers that has the class rotate-me
var rotateMe = document.querySelectorAll('.version-1 .rotate-me');
// define animation duration, this is better than css animationend
var animationDuration = 1000; // milliseconds
// recursive animation sequence
var startSequence = function (classname, items) {
var [first, ...rest] = items;
first.classList.add('rotate');
setTimeout(function () {
if (rest.length > 0) {
startSequence(classname, rest)
}
}, animationDuration);
};
// click handle that starts the sequence
var handleClick = function () {
startSequence('rotate', rotateMe);
};
// check if one rotateMe was matched
if (rotateMe.length > 0) {
// add you action callback to the first match
rotateMe[0].addEventListener('click', handleClick);
}
}
// this version is blocking click before previeous element was clicked
var version2 = function () {
// get all containers that has the class rotate-me
var rotateMe = document.querySelectorAll('.version-2 .rotate-me');
// define animation duration, this is better than css animationend
var animationDuration = 1000; // milliseconds
// active index
var activeElement = 0;
// click handle that starts the sequence
var handleClick = function (index, item) {
if (index === activeElement) {
item.classList.add('rotate');
activeElement += 1;
}
};
for (var i = 0, l = rotateMe.length; i < l; i += 1) {
// add you action callback to the first match
rotateMe[i].addEventListener('click', (function (index, item) {
return function () {
handleClick(index, item);
};
})(i, rotateMe[i]));
}
}
window.onload = function() {
version1();
version2();
}
.wrapper {
display: flex;
}
.rotate-me {
border-radius: 50%;
overflow: hidden;
font-size: 0;
}
.rotate-me:first-child {
cursor: pointer;
}
.rotate-me.rotate {
cursor: initial;
}
.rotate-me.rotate {
transition: transform 1s;
transform: rotate(360deg);
}
<h2>Version 1</h2>
<div class="wrapper version-1">
<div class="rotate-me">
<img src="http://placekitten.com/150/150" alt="kitten placeholder">
</div>
<div class="rotate-me">
<img src="http://placekitten.com/150/150" alt="kitten placeholder">
</div>
<div class="rotate-me">
<img src="http://placekitten.com/150/150" alt="kitten placeholder">
</div>
<div class="rotate-me">
<img src="http://placekitten.com/150/150" alt="kitten placeholder">
</div>
</div>
<h2>Version 2</h2>
<div class="wrapper version-2">
<div class="rotate-me">
<img src="http://placekitten.com/150/150" alt="kitten placeholder">
</div>
<div class="rotate-me">
<img src="http://placekitten.com/150/150" alt="kitten placeholder">
</div>
<div class="rotate-me">
<img src="http://placekitten.com/150/150" alt="kitten placeholder">
</div>
<div class="rotate-me">
<img src="http://placekitten.com/150/150" alt="kitten placeholder">
</div>
</div>
var x = document.getElementById("first");x.addEventListener('click', event => {
x.classList.add("move");
x.addEventListener("webkitAnimationEnd",myEndFunction);
x.addEventListener("animationend",myEndFunction);});
var y = document.getElementById("second");y.addEventListener('click', event => {
y.classList.add("move");
y.addEventListener("webkitAnimationEnd",myEndFunction);
y.addEventListener("animationend",myEndFunction);});
Is this some thing what u are asking for?/
Well might has well put the event listener to the picture itself.
So you know what to rotate.
Yeah even a div can have an event listener.
Query for the div. add an event listener that onclick the animationPlayState should be running. Else by default put it has paused in css.

Make a book reader using images [jquery]

I've been trying for the past hours to create a Comic Book online reader to allow my images to load up.
Everything works fine but I use a counter using a increment method basically and it just doesn't work because bringing down the increments breaks the function.
Maybe there is a simpler way? Also jQuery is the most obscure language to learn unlike HTML or PHP, jQuery has a documentation that pretty much has no organization. Its like here's all the stuff now read each one and maybe you'll find yours. My code is below
<script>
$(function manga () {
var count = 0;
var images = ["source_images/01.jpg", "source_images/02.jpg", "source_images/03.jpg", "source_images/04.jpg", "source_images/05.jpg", "source_images/06.jpg", "source_images/07.jpg"];
$("#left").click(function () {
var img = images[count % images.length];
++count;
$("#manga").attr("src", img);
//alert("clicked");
manga();
});
$("#right").click(function () {
var img = images[count % images.length];
--count;
$("#manga").attr("src", img);
//alert("clicked");
manga();
});
manga();
});
</script>
<title></title>
<center>
<img id="left" style="width:10%; float:left; padding:1.3%" src="files/left_arrow.png" />
<div >
<img id="manga" style="width:75%; float:left" src="source_images/00.jpg" />
</div>
<img id="right" style="width:10%; float:left; padding:1.2%" src="files/right_arrow.png" />
</center>
Basically your calling your function manga 3 times
first when it loads
second when your do left click
and third when you do right click
In this your initializing counter to keep track of the images and everytime
your calling function again your initializing it to 0
so your count again starting from 0.
So to avoid it make your count variable global declare it outside the manga() function.
checkout this code
<script>
var count = 0;
$(function manga () {
var images = ["source_images/01.jpg", "source_images/02.jpg", "source_images/03.jpg", "source_images/04.jpg", "source_images/05.jpg", "source_images/06.jpg", "source_images/07.jpg"];
$("#left").click(function () {
++count;
var img = images[count % images.length];
alert(img);
$("#manga").attr("src", img);
//alert("clicked");
manga();
});
$("#right").click(function () {
if(count == 0)
{
count = images.length-1;
}
else {
--count;
}
var img = images[count % images.length];
alert(img);
$("#manga").attr("src", img);
//alert("clicked");
manga();
});
manga();
});
</head>
<body>
<center>
<center>
<img id="left" style="width:10%; float:left; padding:1.3%" src="files/left_arrow.png" />
<div >
<img id="manga" style="width:75%; float:left" src="source_images/00.jpg" />
</div>
<img id="right" style="width:10%; float:left; padding:1.2%" src="files/right_arrow.png" />
</center>
</center>
I changed the position of count variable in both left and right click. And added one if condition in left click so that when the page loads first time and if user click left arrow first it will show last image.
so image src will move from first to last.It will work.

clearInterval to stop hover animation in jQuery

I have the below fiddle
When I hover over prev I want it to move as it is doing and when I stop hovering I want it to stop.
See the code below. The alert works when I stop hovering but the clearInterval does not?
What am I doing wrong here?
<div> <span id="prev">prev</span>
<div class="scroll-container">
<div class="img-container">
<img src="http://dummyimage.com/100x100/000000/fff">
<img src="http://dummyimage.com/100x100/f33636/fff">
<img src="http://dummyimage.com/100x100/0c5b9e/fff">
<img src="http://dummyimage.com/100x100/0c9e0c/fff">
</div>
</div>
</div>
var hoverInterval;
function goLeft() {
if (!$('.img-container').is(':animated')) {
var first = $('.img-container img:first-child');
var firstClone = first.clone();
$('.img-container').append(firstClone);
$('.img-container').animate({
"left": "-=110px"
}, "slow", function () {
first.remove();
$('.img-container').css("left", "0");
});
}
}
$('#prev').hover(
function () {
hoverInterval = setInterval(goLeft, 100);
},
function () {
alert(1);
clearInterval(goLeft);
}
);
Change it to
clearInterval(hoverInterval);

Adding a CSS class to span tag when corresponding image is slide in

I have a two phase animation including a div full of images and to the right, a paragraph of 10 span sentences. The images are absolute, so they stack on top of each other and have a negative margin initially to hide the image, by overflow: hidden.
On phase 1 (when page loads and before user hovers over a span), the images are set at a 5 second interval per image to loop through the images in an infinite manner. This phase and it's interval will clear when the second phase happens, which is when you hover over a span tag, in which the corresponding image slides in to view.
I have phase 1 and phase 2 coded, but my question is: In phase 1, I have to implement it so that when it's animating through the images by default, the corresponding span tag has to have a CSS class just like when you hover over the span tag in phase 2.
Here is the code if anyone wants to fiddle around with it:
<!--begin:content-->
<div id="content">
<div id="pics">
<img src="ADD ANY IMAGE" id="defaultImg" alt="" />
<img src="ADD ANY IMAGE" id="hover_1_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_2_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_3_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_4_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_5_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_6_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_7_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_8_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_9_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_10_pic" alt="" />
</div>
<!--begin: homeText - block of span tags w/text referenced in jQuery -->
<div class="homeText">
<p>
<span id="hover_1" >evolve water.</span>
<span id="hover_2">stream the party.</span>
<br />
<span id="hover_3">let moms play.</span>
<span id="hover_4">play on big screens.</span>
<br />
<span id="hover_5">turn txt into sport.</span>
<span id="hover_6">have 18 wheels.</span>
<br />
<span id="hover_7">have chapters.</span>
<span id="hover_8">personify an issue.</span>
<br />
<span id="hover_9">transform neighborhoods.</span>
<br />
<span id="hover_10">become keepsakes</span>
</p>
</div>
</div><!--end content-->
CSS
#pics img {
height: 131px;
width: 334px;
position: absolute;
margin-left:-325px;
}
/* ADDED by ben sewards */
#pics {
height:179px;
width:335px;
position: relative;
overflow: hidden;
margin:0px;
padding-top:15px;
margin-left:49px;
float:left;
}
/* ADDED by ben sewards */
.homeText {
width:600px;
height:240px;
padding-left:15px;
padding-top: 10px;
overflow: hidden;
float:left;
}
.homeText p {
line-height: 115%;
font-family: #Adobe Fangsong Std R;
font-size: 2.6em;
font-weight:bolder;
color: #c0c0c0;
margin: 0px;
}
.homeText span:hover {
background-color:Lime;
color: White;
cursor: pointer;
}
.span-background-change {
background-color:Lime;
color: White;
}
JS Script
$('document').ready(function () {
slideIn('defaultImg');
timer = setInterval('slideInNext()', 5000);
functionHover();
});
var slideSpeed = 500;
var slideIn = function (id) {
$('#' + id).addClass('active').animate({ 'margin-left': '0px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true });
}
var slideOutCurrent = function () {
$('#pics img.active').removeClass('active').animate({ 'margin-left': '325px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true, 'complete': function () { $(this).css('margin-left', '-325px'); } });
}
var slideInNext = function () {
var curImage = $('#pics img.active');
var nextImage = curImage.next();
if (nextImage.length == 0) {
nextImage = $('#pics img:first');
}
slideOutCurrent();
slideIn(nextImage.attr('id'));
}
var queueToSlideIn = [];
var mouseOnTimer = null;
var mouseOffTimer = null;
var functionHover = function () {
$('.homeText span').hover(
//binding 2 handlers to hover event
function () { //when hovering over a span - mousenenter
clearTimeout(mouseOffTimer);
clearInterval(timer);
var thisId = $(this).attr('id');
mouseOnTimer = setTimeout(function () {
if (!$('#' + thisId + '_pic').hasClass('active')) {
addToQueue(thisId + '_pic');
}
}, 300);
},
function () { //when off of span - mouseleave
clearTimeout(mouseOnTimer);
mouseOffTimer = setTimeout(function () {
if (!$('#defaultImg').hasClass('active')) {
addToQueue('defaultImg');
}
}, 500);
}
);
$('.homeText span').click(function () {
//set current span on click
$span = $(this).attr('id');
//navigate to corresponding case study
var href = $('#' + $span + '_pic').attr('alt');
window.location.href = href;
});
}
var addToQueue = function (id) {
queueToSlideIn.push(id);
$('#pics').queue(function () { animateNext(); $(this).dequeue(); }).delay(slideSpeed);
}
var animateNext = function () {
if (queueToSlideIn.length > 0) {
var id = queueToSlideIn.shift();
slideOutCurrent();
slideIn(id);
}
};
Sorry if the indenting is messy.
Ben
I added anew class which is a duplicate of your hover class:
.homeText-hover {
background-color:Lime;
color: White;
cursor: pointer;
}
Then I added two line each to your SlideIn and slideOutCurrent functions:
var slideIn = function (id) {
var slId = id.split('_pic');
$('#' + slId[0]).addClass('homeText-hover');
$('#' + id).addClass('active').animate({ 'margin-left': '0px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true });
}
var slideOutCurrent = function () {
var slId = $('#pics img.active').attr('id').split('_pic');
$('#' + slId[0]).removeClass('homeText-hover');
$('#pics img.active').removeClass('active').animate({ 'margin-left': '325px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true, 'complete': function () { $(this).css('margin-left', '-325px'); } });
}
Your autoslide isn't working out in FF...
I like your solution, Ben. Another solution that uses the same principle of selecting identifying attributes would be to add a class, unique to each img-span pair, to each of the elements, so that each shares a specific class with its corresponding element.
Below is an explanation of the use of classes as flags, which I originally posted in a solution to a different question that has since been closed:
Classes as Flags
Adding a class to an element does not always mean that you are going to be giving it some new CSS styles. CSS is a language that USES CLASSES in order TO HELP identify elements to style a particular way; classes are NOT FOR THE SOLE PURPOSE of applying CSS to an element. Were this not the case, CSS would only be able to style elements through the use of classes, and not through the use of other selectors (IDs, parents, children, descendants, etc.).
Developers often use classes as "flags." Flags are a way of signaling something about a particular element without having to store that information in a variable. For example, imagine you have a list of elements and all the elements are styled exactly the same, via a CSS class. If a developer wanted to mark every other element in this list in a particular way (for some later use), without changing the style of the elements, he may choose to add a second class called "alternate" to the elements.
You can add as many classes as you want to an element and it is totally accepted coding style to add multiple classes that do not have any associated styles (provided that such classes are for some other use -scripting, etc.).
Added this snippet of code to my slideInNext function for desired results:
if (nextImage.attr('id') != "defaultImg") {
//add class to corresponding span tag of current image
var spanId = nextImage.attr('id');
//corresponing span of next image
spanId = spanId.substring(0, spanId.length - 4);
$('#' + spanId).addClass('span-background-change');
}
I just used the substring method in javascript to pull apart the images attribute id and place it in a local variable to represent the span id.

Categories