change image after x seconds with loop mouseenter jQuery [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have an image in HTML, and I wish when the mouse enter in image, this image change quickly, with an infinite loop. I have a lot of image to display (logo_white, logo_red, logo_blue, logo_green, ...)
HTML
<img src="img/logo_white.png" alt="Logo" id="logo" />
JS
$('#logo').mouseenter(function() {
var src = ($(this).attr('src') === 'img/logo_white.png')
? 'img/logo_red.png'
: 'img/logo_white.png';
$(this).attr('src', src);
});
This JS code "work". But I think it could be better.
Thanks you in advance for your response.

Not a 100% sure what you mean, but maybe an example like this is what you are looking for or can get you started.
This example:
Create an array with the links to your images
Preload these images
For the 'mouseenter' event start an interval and switch the logo to the next one in the array (Or continue where it left off)
For the 'mouseleave' event, stop the interval.
Initializes the first image when the page is fully loaded including graphics. https://api.jquery.com/load-event/
You can change the variable intervalInMilliseconds to speed it up or slow it down.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var interval;
var currentImageNumber = 0;
var intervalInMilliseconds = 1000;
var images = [
"img/logo_green.png",
"img/logo_blue.png",
"img/logo_red.png",
"img/logo_white.png"
];
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
(new Image()).src = this;
});
}
function switchLogo(imageNumber) {
$('#logo').attr('src', images[imageNumber]);
currentImageNumber = currentImageNumber === images.length -1 ? 0 : ++currentImageNumber;
}
preload(images);
$(document).ready(function() {
var logo = $('#logo');
logo.mouseenter(function() {
interval = window.setInterval(function () {
switchLogo(currentImageNumber)
}, intervalInMilliseconds);
});
logo.mouseleave(function() {
clearInterval(interval);
});
});
// When all the images are loaded
$(window).load(function() {
// Initialize this to the first image
switchLogo(currentImageNumber);
});
</script>
</head>
<body>
<img src="" alt="Logo" id="logo" />
</body>
</html>

Related

is it possible to add 3 photos to this code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
for this task i have to get 3 photos and make a button to cycle through the photos new i need to make it so that i can use photos from my file
.Every little helps :D
<!DOCTYPE html>
<html>
<body>
<img id="light" src="Red.png">
<script>
var list= ['Green.png', 'Yellow.png', 'Red.png'];
var i = 0;
function lightsCycle() {
i = i + 1;
i = i % list.length;
var light = document.getElementById("light").src = list[i];
}
</script>
<button type = "button" onclick="lightsCycle()">Next Light</button>
</body>
</html>
UPDATE: I have modified my code to attempt one of the answers given here, but I am still having trouble:
<!DOCTYPE html>
<html>
<body>
<img id="light" src="Red.png">
<script>
var list= ['https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png',
'https://img.clipartfox.com/837fed127e3383c2a61cf08f76a65081_pics-for-stop-light-yellow-clipart-traffic-light-yellow_641-880.png',
'http://previews.123rf.com/images/blojfo/blojfo1003/blojfo100300021/6559248-Traffic-light-with-red-light-Stock-Photo.jpg'];
var i = 0;
function lightsCycle() {
i = (i < list.length - 1) ? ++i : 0;
document.getElementById("light").src = list[i];
}
</script>
<img id="light" src="https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png">
<button type = "button" onclick="lightsCycle()">Next Light</button>
</body>
</html>
In your function, you are incrementing i and then immediately throwing that value away on the next line where you are setting i to the modulo of i and the length of your array. That line is not needed.
You also need to check to see if i is at the highest index number that the array supports and, if so, reset it to 0.
Next, the line:
var light = document.getElementById("light").src = list[i];
unnecessarily declares a variable called light since you never use it anywhere.
Lastly, don't use HTML attributes to hook up event handlers (onclick, onmouseover, etc.) as they:
create spaghetti code (HTML and JavaScript mixed on the same line) that is difficult to read and maintain.
create globally scoped wrapper functions around your attribute's value that alter the this binding and can cause your function to not work correctly.
don't follow W3C standards for event handling.
// Put the correct relative paths to your images back into the array. Here, I'm substituting
// online images so that you can see the code working properly.
var list= ['https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png',
'https://img.clipartfox.com/837fed127e3383c2a61cf08f76a65081_pics-for-stop-light-yellow-clipart-traffic-light-yellow_641-880.png',
'http://previews.123rf.com/images/blojfo/blojfo1003/blojfo100300021/6559248-Traffic-light-with-red-light-Stock-Photo.jpg'];
var i = 0;
// Only scan the document one time to get a reference to the image element.
// It's a waste of resources to do it every time the button is clicked
var img = document.getElementById("light");
var btn = document.getElementById("btn")
// Don't use HTML attributes to hook up event handlers (onclick, onmouseover, etc.)
btn.addEventListener("click", lightsCycle);
function lightsCycle() {
// If i is less than the max index, increment it, otherwise set it to zero
i = (i < list.length - 1) ? ++i : 0;
// Set the source of the image element to the next array value
img.src = list[i];
}
img { width:50px; }
<img id="light" src="https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png">
<button type="button" id="btn">Next Light</button>

How to make a simple slideshow in JS?

I'm trying to make a simple slideshow with JavaScript.
Here is my index.html
<body>
<h1>Slideshow example</h1>
<button onclick="slideshow.timer()">Next slide</button>
<div id="container"></div>
<script src="slide.js"></script>
</body>
And here is slide.js
var slideshow = {
sliderImages: ["img/img1.png", "img/img2.png"],
timer: function() {
this.sliderImages.forEach(function(img) {
var container = document.getElementById('container');
var image = document.createElement('img');
container.appendChild(image);
image.src= img;
})
}
}
If I click the "next slide" button, I see both of the images. It loops through the whole array. How could I make it loop through the array just once, when clicking the button?
I tried adding container.innerHTML = ''; so that the previous image would be removed when adding the next image, but that resulted it showing immidietly the image in sliderImages[1]. Am I approaching this whole thing wrong?
I updated your code. It is not the best way to write it but I just modified your example to show you the problem. The problem is your timer function which is just going through all the elements in the array at once. Instead what you may want to do is add some delay.
var slideshow = {
sliderImages: ["img/img1.png", "img/img2.png"],
currentImgIndex: 0,
timer: function() {
if (this.currentImgIndex < this.sliderImages.length ) {
var image = document.getElementById('img');
image.src= this.sliderImages[this.currentImgIndex];
this.currentImgIndex++;
setTimeout(function (){ slideshow.timer()}, 2000)
} else {
alert("no more images");
}
}
}
<body>
<h1>Slideshow example</h1>
<img id="img"/>
<button onclick="slideshow.timer()">Next slide</button>
<div id="container"></div>
<script src="slide.js"> </script>
</body>
If you are going to change the images only when the button is clicked, you don't need the forEach loop. If you are going to change images without user interaction then you need the loop but you need setInterval also.

Update parts of an html page based on the location.href client-side [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have tried searching and nothing I am finding works. the site this is for does NOT work with php, I know how to with php, but I need any other way.
I just want a simple IF THEN statement to say if website is www.a.com then "this style sheet" "this page title" "this logo", etc. I will use the if function many times through the page. if site is a.com, this image, this text, etc. if is b.com, then everything is different.
I also want it to only recognize the domain itself, so if on a.com/thispage.html , then it would still load with the proper data.
reason being, I have two site pointed to the same folder, which is a store, same product, etc. however we market the product as 'a' and as 'b'. so I just want to see what site the user is on and pull the proper info regarding that site.
this is what I have come up with, but does not generate the required html.
<script>
window.onload = function ()
var element = document.getElementbyId('idElement');
if (location.href == "a.com")
{
<link href="/landing.css" rel="stylesheet" type="text/css" />
}
if (location.href == "b.com")
{
<link href="/landing2.css" rel="stylesheet" type="text/css" />
}
</script>
<script>
if (location.href == "a.com")
{
<title>AAAAAAAAAAAAA</title>
}
if (location.href == "b.com")
{
<title>BBBBBBBBBBBBB</title>
}
</script>
<script>
if (location.href == "a.com")
{
<img src="a.png">
}
if (location.href == "b.com")
{
<img src="b.png">
}
</script>
etc, etc, etc
You can achieve this by having an array that holds an object with metadata about each site. When the script runs you create a new link element for the css and add it to the head and set the document title.
Do notice that DOM content can only be found (and then changed) after it is loaded, hence the use of an eventlistener for DOMContentLoaded.
This leads to the following implementation in the html script tag:
<html>
<head>
<title>
NotSet
</title>
<script>
(function () {
"use strict";
// have an array sites with data
var sites = [{
url: 'a.com', // if location.href contains this
title: 'AAAAAAAAAAAAA', // use this title
css: '/landing.css', // use this css file
images: [{id: 'idOfImage', src: 'a.png'}] // replace those ids with src
}, {
url: 'b.com',
title: 'BBBBBBBBBBBBB',
css: '/landing2.css',
images: [{id: 'idOfImage', src: 'b.png'}]
}
],
site, siteIndex, NOT_FOUND = -1;
//create a link for the css and add it
function addLink(css) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = css;
document.head.appendChild(link);
}
// find the img tags by id and set the src
function setImages(images) {
var image, imgIndex, img;
for (imgIndex = 0; imgIndex < images.length; imgIndex = imgIndex + 1) {
image = images[imgIndex];
img = document.getElementById(image.id);
if (img !== null) {
img.src = image.src;
}
}
}
// iterate over our sites array
// at the end site will have an object or is null (if no match found)
for (siteIndex = 0; siteIndex < sites.length; siteIndex = siteIndex + 1) {
site = sites[siteIndex];
// is url found in location.href
if (window.location.href.indexOf(site.url) > NOT_FOUND) {
break;
}
site = null;
}
// if we have a site do what is needed
if (site !== null) {
addLink(site.css);
// IE9 or up...
document.addEventListener("DOMContentLoaded",
function () {setImages(site.images); }
);
// set the title
document.title = site.title;
}
}());
</script>
</head>
<body>
Does this work?
<img id="idOfImage" src="none.png" />
</body>
<html>

How do I create 9 images on the same page that switch every 5 seconds between 3 images. I can do one but can not do multiple [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
<script type="text/javascript">
var currPic = 1;
var totPics = 3;
var keepTime;
function setupPicChange() {
keepTime = setTimeout("changePic()", 5000);
}
function changePic() {
currPic++;
if (currPic > totPics) currPic = 1;
document.getElementById("picture1").src = "advert" + currPic + ".jpg";
setupPicChange();
}
</script>
Hello this is my script to have an image that changes three times after 5 seconds, it works perfectly, but can somebody in very simple terms show me how to make this apply to 9 different images, all changing 3 times, at the same time, but to different images?
eg advert 1, will change to advert 2, and then to advert 3................
below it................. advert 4 will change to advert 5 and then to advert 6................ below that ........................ advert 7 will change to advert 8 and then to advert 9......... all the way up to advert 27. They wont actually be adverts, thats just a good example of what I need to know.
Thanks once again guys!!!!
You should think about abstracting the logic you're currently using to apply to a set of images in general. Here's an example:
<script type="text/javascript">
var rotators = [
{ id: 'picture1', images: ['pic1.jpg', 'pic2.jpg', 'pic3.jpg'], selectedIndex: 0 },
{ id: 'picture2', images: ['pic4.jpg', 'pic5.jpg', 'pic6.jpg'], selectedIndex: 0 },
{ id: 'picture3', images: ['pic7.jpg', 'pic8.jpg', 'pic9.jpg'], selectedIndex: 0 }
];
var updateImages = function() {
for (var i=0; i < rotators.length; i++) {
var rotator = rotators[i];
rotator.selectedIndex++;
if (rotator.selectedIndex >= rotator.images.length) {
rotator.selectedIndex = 0;
}
document.getElementById(rotator.id).src = rotator.images[rotator.selectedIndex];
}
};
var timer = setInterval(updateImages, 5000);
</script>
This makes the components you're currently operating on (the id of the image you want to change, the images you want to rotate through, and your current position in those images) properties of objects that are placed in an array. Then the function that does the updating (like your changePic method) can loop over all of those objects in the array and use the same logic to update each of them.
I also changed the setTimeout call to setInterval, which will call the provided function every X ms, instead of calling it just once and then having to reset the timer.

when mouse over image slide is start as gif image

I have 5 images in a same folder.
1.jpg,2.jpg,3.jpg,4.jpg,5.jpg
I will be show only one image on my webpage.
example
<body>
<img src="1.jpg">
</body>
when visitor is mouse over on image, image will be change to 2.jpg and,3.jpg and....will be stop at 5.jpg.Slideshow is similar as a gif image.
Please How to write javascript or jquery .
Please tell me simplest way.
Thank my dear friend.
I found simalor question in this website.But I can't found complete answer for me.
If this question is duplicate, so sorry
please forgive me for my poor english useage.
You can use jQuery's hover event and pass in the onenter and onout methods. On enter you can call and setup an interval to increment the number of your image, and on out you want to stop it by clearing your interval.
<!DOCTYPE html>
<html>
<head>
<title>image</title>
</head>
<body>
<img id="img" src="1.jpg" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var interval = null;
function changeImage(){
var nextNum = parseInt($('#img').attr('src').replace('.jpg',''), 10) + 1;
// If you want it to repeat back to 1 after 5
nextNum = nextNum > 5 ? 1 : nextNum;
$('#img').attr('src', nextNum+'.jpg');
}
$('#img').hover(
function(){
// Call change Image every 50ms
interval = setInterval(changeImage, 50);
changeImage();
},
function(){
// Stop the call
interval && clearInterval(interval);
}
);
</script>
</body>
</html>​​​​​​​​​​​​

Categories