jquery issue: how to break and reset setinterval? - javascript

I created a image loop by using jquery and it works fine. Here is my code.
$(document).ready(function(){
$('.images').hide();
$('#image1').show('slide', {direction: 'right'}, 500);
$('#image1').delay(2000).hide('slide', {direction: 'left'}, 500);
var sc = $('#image img').size();
var count = 2;
setInterval(function(){
$('#image'+count).show('slide', {direction: 'right'}, 500);
$('#image'+count).delay(2000).hide('slide', {direction: 'left'}, 500);
if(count == sc){
count = 1;
}else{
count = count + 1;
}
}, 3000);
$('.name').click(function(){
var name = $(this).attr('id');
name = name.replace('name', '');
count = name;
});
});
Here is the html code.
<div id="image">
<img class="images" id="image1" alt="Image loop" src="image1.jpg" width="550px" height="400px"/>
<img class="images" id="image2" alt="Image loop" src="image2.jpg" width="550px" height="400px"/>
<img class="images" id="image3" alt="Image loop" src="image3.jpg" width="550px" height="400px"/>
<img class="images" id="image4" alt="Image loop" src="image4.jpg" width="550px" height="400px"/>
<img class="images" id="image5" alt="Image loop" src="image5.jpg" width="550px" height="400px"/>
</div>
<div id="name">
<div class="name" id="name1">
<img src="image1.jpg" width="80px" height="80px"/>
</div>
<div class="name" id="name2">
<img src="image2.jpg" width="80px" height="80px"/>
</div>
<div class="name" id="name3">
<img src="image3.jpg" width="80px" height="80px"/>
</div>
<div class="name" id="name4">
<img src="image4.jpg" width="80px" height="80px"/>
</div>
<div class="name" id="name5">
<img src="image5.jpg" width="80px" height="80px"/>
</div>
The css controls the name sets to the right. My idea is, click the small image on the right to immediately switch the image which user choose.
It seems working a little bit. The setInterval is still runing and the loop is ruined. How can I deal with this properly? Here is the jsfiddle link. Thanks!

You can stop setInterval from running with clearInterval. Specifically, you need to call it on the return value of setInterval.
var interval = setInterval(...
clearInterval(interval);
EDIT: this doesn't apply directly to your problem. What you can do is just create a separate function that does the callback to setInterval. Then, also call that function as part of the callback to the click event. Whether you want to clear the interval or not (halt the animation) is up to you.

The problem occurs because you change the type of count from a number to a string inside your click handler - when you assign name to count. I've edited your code to include parseInt.
$('.name').click(function(){
var name = $(this).attr('id');
name = name.replace('name', '');
count = parseInt(name, 10);
});

Here's a simple working example
var interval;
var times;
function doSomething() {
if (times == 100) {
// Unset the interval:
clearInterval(interval);
} else {
alert("Hey");
times++;
}
}
// Initialize interval:
interval = setInterval(doSomething, 1000);

Related

How do I change image B's src to Image A's src when Image A is clicked with Javascript?

Goal: When image A is clicked that same image appears at the bottom of the page. Needs to work for more than one image.
When image A is clicked I need image B to now have the same src as image A.
Or to Generate a copy of the clicked image.
This should also be able to work for several pictures.
So for example if I clicked 5 images (Image A-01, A-02, A-03, A-04, A-05) on the screen....
At the bottom of the page there should be those 5 images
I've tried
HTML:
<img id="myImage" src="http://placehold.it/150">
<img id="new" src="http://placehold.it/200">
JS
$(function(){
$("#myImage").click(function() {
$("#new").attr("src","http://placehold.it/150")
});
});
Which works to replace one image but I need the same code to work for multiple image clicks.
Another proposal with an event listener.
var imgCount = 5,
i;
for (i = 1; i <= 5; i++) {
document.getElementById('img' + i).addEventListener('click', setImg('img' + i), false);
}
function setImg(id) {
return function () {
var img = document.createElement('img');
if (imgCount) {
imgCount--;
img.src = document.getElementById(id).src;
document.getElementById('footer').appendChild(img);
};
}
}
<img id="img1" src="http://lorempixel.com/200/100/city/1" />
<img id="img2" src="http://lorempixel.com/200/100/city/2" />
<img id="img3" src="http://lorempixel.com/200/100/city/3" />
<img id="img4" src="http://lorempixel.com/200/100/city/4" />
<img id="img5" src="http://lorempixel.com/200/100/city/5" />
<div id="footer"></div>
This will help you out
function changeSrc(id){
document.getElementById('footer').src = document.getElementById(id).src;
}
<img src="http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/sample1_l.jpg" height="200" width="auto" id="img1" onclick="changeSrc(this.id)"/>
<img src="https://images-eu.ssl-images-amazon.com/images/G/02/uk-electronics/product_content/Nikon/ECS-NK1308141-B00ECGX8FM-2L-1024w683q85s10-BKEH_London_Paris__0316.jpg" height="200" width="auto" id="img2" class="image" onclick="changeSrc(this.id)"/>
<img src="" height="200" width="auto" id="footer" class="image" />
Try this:
<img src="https://randomuser.me/api/portraits/thumb/men/57.jpg" class="a">
<img src="https://randomuser.me/api/portraits/thumb/women/14.jpg" class="a">
<img src="https://randomuser.me/api/portraits/thumb/women/7.jpg" class="a">
<br>
<div id="sectionB">
<img src="http://placehold.it/48" class="b">
<img src="http://placehold.it/48" class="b">
<img src="http://placehold.it/48" class="b">
</div>
<br>
<button id="reset">Reset</button>
===
$(function() {
$('.a').click(function() {
var img = $(this).attr('src');
var index = $(this).index();
$('.b').eq(index).attr('src', img);
})
$('#reset').click(function(){
$('.b').attr('src', 'http://placehold.it/48');
})
})
DEMO: https://jsfiddle.net/j359yfor/

Assign a divs id to a variable

I have built rock paper scissors to run in a terminal/console window using prompts and alerts. I am now in the process of converting the game into something that is playable in a web browser with the use of the jQuery library.
To accomplish this I have made images of each of the hands: Rock paper & scissors. Now, I want a user to click on one of the hands and assign that move to a variable named move. Here is my code:
HTML:
<div class="grow pic">
<img src="rock.png" class=id="rock" alt="rock" height="75" width="75">
</div>
<div class="grow pic">
<img src="paper.png" id="paper" alt="paper" height="75" width="75">
</div>
<div class="grow pic">
<img src="scissor.png" id="scissors" alt="scissors" height="75" width="75">
</div>
And the jQuery I'm trying to implement:
var move;
$( "#id" ).click(function() {
move = $(this).attr('id');
});
So the question here, is how exactly do I make the id of an image assign to a variable named move. I keep getting an error saying "Uncaught ReferenceError: move is not defined(…)".
This makes no sense:
$( "#id" ).click(function() {
It attempts to select an element with the ID value 'id'. Instead, target images that are descendants of elements with a common class:
$('.pic img').click(function() {
Now your function should work as it is.
You may use this like:
$("div img").click(function(){
var move = $(this).attr('id');
});
var move;
$( ".id" ).click(function() {
move = $(this).attr('id');
$('#result').html(move);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grow pic">
<img src="rock.png" class=id id="rock" alt="rock" height="75" width="75">
</div>
<div class="grow pic">
<img src="paper.png" class=id id="paper" alt="paper" height="75" width="75">
</div>
<div class="grow pic">
<img src="scissor.png" class=id id="scissors" alt="scissors" height="75" width="75">
</div>
<div id=result></div>
Run the click event against the class
try
var move = document.getElementsByTagName(this).getAttribute("id");

How to swap an image with another when hovering on the other image?

I have 5 small images and 1 image that is twice the size as the small ones. What I'm trying to do is whenever you hover on the small images the big image changes to the image you are hovering. I am having a hard time searching for methods and functions but luck as of yet. this is what I have
<div class="bigImg">
<img id="image0" src="images/image1.png">
</div>
<img id="image1" src="images/image1.png">
<img id="image2" src="images/image2.png">
<img id="image3" src="images/image3.png">
<img id="image4" src="images/image4.png">
<img id="image5" src="images/image5.png">
I was trying to add this function that I saw somewhere else here
function mouseOver() {
document.getElementById("image0").innerHTML = '<"image2.png"/>';
}
function mouseOut() {
document.getElementById("image0").innerHTML = '<img src="image1.png" />';
}
I wrote the img tag as
<img id="image1" onmouseover="mouseOver()" onmouseout="mouseOut()" src="images/image1.png">
for all of the images but wasn't working. Can someone steer me in the right direction, please?
This is how I did it:
function mouseOut() {
document.getElementById("image0").src = 'http://lorempixel.com/g/600/600/';
}
function changePic(elem) {
document.getElementById("image0").src = elem.src;
}
Here is the JSFiddle demo
If you want to do it using Jquery you can try this.
<div class="bigImg"></div>
<img class="imgLink" src="http://dummyimage.com/100x100/eb00eb/fff" target="http://dummyimage.com/100x100/eb00eb/fff">
<img class="imgLink" src="http://dummyimage.com/100x100/000/fff" target="http://dummyimage.com/100x100/000/fff">
<img class="imgLink" src="http://dummyimage.com/100x100/999/fff" target="http://dummyimage.com/100x100/999/fff">
JS
$('.imgLink').hover(function(){
$('.bigImg').css({'background':'url('+ $(this).attr('target') +')'});
},function(){
$('.bigImg').css({'background':''});
});
Demo here
Basic concept behind this is we have to catch mouseover and mouseout events. Now, on mouse over we have to change the src attribute of that particular Image and vice versa for getting back the original image.
Try this one :
function mouseOver(element) {
document.getElementById(element).src = 'https://www.google.co.in/images/google_favicon_128.png';
}
function mouseOut(element) {
document.getElementById(element).src = 'https://cdn0.iconfinder.com/data/icons/yooicons_set01_socialbookmarks/128/social_google_box.png';
}
<div class="bigImg"><img id="image0" src="https://cdn0.iconfinder.com/data/icons/yooicons_set01_socialbookmarks/128/social_google_box.png"></div>
<img id="image1" onmouseover="mouseOver('image1')" onmouseout="mouseOut('image1')" src="https://cdn0.iconfinder.com/data/icons/yooicons_set01_socialbookmarks/128/social_google_box.png">
<img id="image2" onmouseover="mouseOver('image2')" onmouseout="mouseOut('image2')" src="https://cdn0.iconfinder.com/data/icons/yooicons_set01_socialbookmarks/128/social_google_box.png">
<img id="image3" onmouseover="mouseOver('image3')" onmouseout="mouseOut('image3')" src="https://cdn0.iconfinder.com/data/icons/yooicons_set01_socialbookmarks/128/social_google_box.png">
<img id="image4" onmouseover="mouseOver('image4')" onmouseout="mouseOut('image4')" src="https://cdn0.iconfinder.com/data/icons/yooicons_set01_socialbookmarks/128/social_google_box.png">
<img id="image5" onmouseover="mouseOver('image5')" onmouseout="mouseOut('image5')" src="https://cdn0.iconfinder.com/data/icons/yooicons_set01_socialbookmarks/128/social_google_box.png">

jQuery automatic scroll through images

I'm creating a simple little slideshow for a site I'm designing for a friend. So far I have it to work just perfectly via clicking images to show / hide the respective image. I'm trying to get it to automatically scroll through the images but it won't seem to work. Here's my code:
<script type="text/javascript">
$(function() // run after page loads
{
$('.slide1t').show();
$('.slide2').click(function()
{
$('.slide2t').show();
$('.slide1t').hide();
$('.slide3t').hide();
$('.slide4t').hide();
});
$('.slide1').click(function()
{
$('.slide1t').show();
$('.slide2t').hide();
$('.slide3t').hide();
$('.slide4t').hide();
});
$('.slide3').click(function()
{
$('.slide3t').show();
$('.slide1t').hide();
$('.slide2t').hide();
$('.slide4t').hide();
});
$('.slide4').click(function()
{
$('.slide4t').show();
$('.slide1t').hide();
$('.slide2t').hide();
$('.slide3t').hide();
});
});
</script>
This is the code i'm using to hide/show images when clicked. Could this be shortened using toggle?
This is what i've tried to get them automatically scrolling:
<script type="text/javascript">
$(function() // run after page loads
{
$('.slide1t').show([1000]),
$('.slide1t').hide(),
$('.slide2t').show([1000]),
$('.slide21t').hide(),
$('.slide3t').show([1000]),
$('.slide3t').hide(),
$('.slide4t').show([1000]),
$('.slide4t').hide()
});
</script>
I've tried other aspects of this same code to try and get it to do something, but to no anvil.
<div id="slideshow">
<div class="text">
<a class="slide1" href="#"><img src="images/1.png" width="240" height="60" /></a>
<a class="slide2" href="#"><img src="images/2.png" width="240" height="60" /></a>
<a class="slide3" href="#"><img src="images/3.png" width="240" height="60" /></a>
<a class="slide4" href="#"><img src="images/4.png" width="240" height="60" /></a>
</div>
<div class="image">
<a class="slide1t" href="#"><img src="images/image1.png" width="525" height="210" /></a>
<a class="slide2t" href="#"><img src="images/image1.png" width="525" height="110" /></a>
<a class="slide3t" href="#"><img src="images/image1.png" width="525" height="170" /></a>
<a class="slide4t" href="#"><img src="images/image1.png" width="525" height="190" /></a>
</div>
</div>
I've looked into the documentation and saw you can use .show([duration],[easing],[callback]) but I don't really know what to input into them.
Thanks all
Are you making a slideshow where you can see to previous and next slide to the left and right of the current slide, or just one slide fading into another?
If it's the latter you can use this very simple code for doing this.
HTML:
<div class="image">
<img src="images/image1.png" />
<img src="images/image2.png" />
<img src="images/image3.png" />
<img src="images/image4.png" />
</div>
CSS:
.image
{
position:relative;
}
.image img
{
position:absolute;
top:0;
left:0;
}
jQuery:
$(function() {
$('.image img:gt(0)').hide(); // to hide all but the first image when page loads
setInterval(function()
{
$('.image :first-child').fadeOut(1000)
.next().fadeIn(1000).end().appendTo('.image');
},5000);
}
This basically shuffles the images like a pack of cards. 5000 (5 seconds) is the interval between fading, 1000 (1 second) is the speed of the fading animation.
For this to work however you must use position:relative on the containing div and position:absolute to position the images on top of each other.
jsFiddle demo
The thing is, .show is async. So your javascript will continue will it does the effect. That's what the third parameter is for, it's an anonymous function that will get called when the effect has finished.
You should look into a jquery plugin, making this things yourself is wasting time. There are hundreds of these plugins so there is always one fitting your needs.
For example: http://www.1stwebdesigner.com/css/fresh-jquery-image-gallery-display-solutions/
You can do this:
$('.image a').each(function (index) {
$(this).show(1000, function () {
$(this).delay(index * 1000).hide(1000);
});
});
FIDDLE DEMO
If you don't want to change your structure much and still want to retain the click function, you can do something like this
This is similar to your original approach but is based in a function and element's siblings instead of doing each image individual. This is optimized for adding new elements easily and retaining functionality. I used a setInterval to loop the animation function as well
HTML (changed slightly)
<div id="slideshow">
<div class="text"> <a id='one' href="#"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Small-city-symbol.svg/348px-Small-city-symbol.svg.png" width="240" height="60" /></a>
<a id='two' href="#"><img src="https://si0.twimg.com/profile_images/604644048/sign051.gif" width="240" height="60" /></a> <a id='three' href="#"><img src="https://g.twimg.com/business/page/image/11TwitterForSmallBusiness-300_1.png" width="240" height="60" /></a> <a id='four' href="#"><img src="https://si0.twimg.com/profile_images/2204583306/fb_logo.png" width="240" height="60" /></a>
</div>
<div class="image"> <a id='one' href="#"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Small-city-symbol.svg/348px-Small-city-symbol.svg.png" width="525" height="210" /></a>
<a id='two' href="#"><img src="https://si0.twimg.com/profile_images/604644048/sign051.gif" width="525" height="110" /></a>
<a id='three' href="#"><img src="https://g.twimg.com/business/page/image/11TwitterForSmallBusiness-300_1.png" width="525" height="170" /></a>
<a id='four' href="#"><img src="https://si0.twimg.com/profile_images/2204583306/fb_logo.png" width="525" height="190" /></a>
</div>
</div>
CSS:
.image a:not(#one) {
display:none;
}
javascript:
$('.text a').click(function () {
var idName = $(this).attr('id');
$('.image a').each(function () {
if ($(this).attr('id') === idName) $(this).show(1000);
else {
$(this).hide(1000);
}
});
window.clearInterval(loop);
loop = self.setInterval(function () {
autoChangeSlide()
}, 5000);
});
function autoChangeSlide() {
var elem;
$('.image a').each(function () {
if ($(this).is(':visible')) elem = $(this);
});
if (elem.attr('id') != $('.image').children('a').last().attr('id')) {
elem.hide(1000).next().show(1000);
} else {
elem.hide(1000).parent().children('a').first().show(1000);
}
}
var loop = self.setInterval(function () {
autoChangeSlide()
}, 5000);
You can combine my solution with Dolchio's to make it particularly awesome

JQuery click() strange behavior

I want to make a simple photo gallery function. However, there are some strange behavior of JQuery's click().
After the user clicks the forward button, 10 next images should be shown. After the user clicks the backward button, 10 previous images should be shown.
In the following code, 4 lines which works fine in my code are commented. I expect the JQuery click() should do the same thing as the commented lines, but it doesn't. Code using JQuery click() doesn't work after I click backward and forward several times. I want to ask where's the problem of the code. Thank you.
<script type="text/javascript">
$(document).ready(function() {
var numImages = imagesObj.images.image.length;
var imagePath = "images/";
var currentIndex = 0;
function changeImageList(startIndex){
var imageIndex = 0;
$("#imagesList img").css("display","none");
for (var i=startIndex; i<numImages && i<startIndex + 10; i++)
{
var imageId = "image" + imageIndex;
var image = imagesObj.images.image[i];
$("#" + imageId).attr("src",imagePath + image.imageurl).css("display","");
imageIndex++;
}
currentIndex = startIndex;
if (numImages > currentIndex+10){
$('#forward').css("cursor","pointer");
//document.getElementById("forward").onclick = function(){changeImageList(currentIndex+10);};
$('#forward').click(function(){ changeImageList(currentIndex+10);});
}else{
$('#forward').css("cursor","default");
//document.getElementById("forward").onclick = function(){};
$('#forward').click(function(){});
}
if (currentIndex < 10){
$('#backward').css("cursor","default");
//document.getElementById("backward").onclick = function(){};
$('#backward').click(function(){});
}else{
$('#backward').css("cursor","pointer");
//document.getElementById("backward").onclick = function(){changeImageList(currentIndex-10);};
$('#backward').click(function(){changeImageList(currentIndex-10);});
}
}
changeImageList(0);
});
</script>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center"><img id="backward" src="images/lft_arrow.gif" alt="" width="39" height="44" /></td>
<td id="imagesList" align="center">
<img id="image0" width="77" style="display:none; cursor:pointer" />
<img id="image1" width="77" style="display:none; cursor:pointer" />
<img id="image2" width="77" style="display:none; cursor:pointer" />
<img id="image3" width="77" style="display:none; cursor:pointer" />
<img id="image4" width="77" style="display:none; cursor:pointer" />
<img id="image5" width="77" style="display:none; cursor:pointer" />
<img id="image6" width="77" style="display:none; cursor:pointer" />
<img id="image7" width="77" style="display:none; cursor:pointer" />
<img id="image8" width="77" style="display:none; cursor:pointer" />
<img id="image9" width="77" style="display:none; cursor:pointer" />
</td>
<td align="center"><img id="forward" src="images/rgt_arrow.gif" alt="" width="39" height="44" /></td>
</tr>
</table>
</body>
This is the normal behaviour of event binding : when you call click, the event callback is added to the element and does not replace existing callbacks. When you click backward and forward buttons multiple times, you assign multiple handlers for the click event and now you know that this is bad :)
There are two solutions to you problem :
use eg $('#backward').unbind('click') before you assign a new event, this is the easy fix for your code.
assign only one event to the buttons with a relative index, eg $('#backward').click(function(){ changeImageList(-10);});. I find it cleaner will a simple check at the beginning of changeImageList to calculate startIndex, but you'll still have to set the cursor to default/pointer.

Categories

Resources