First time JavaScript coder here.
Trying to solve this so that an image is displayed when the appropriate button for that image is clicked and then the function continues to show the other image in the Array and loops.
For instance if the banner is displaying image 4 and the user clicks on the button for image 2, then the banner should display image 2 and then rotate to show image 3 and continue looping.
Here is the code:
var i = 0;
var baners = new Array();
baners.push('banner1.jpg');
baners.push('banner2.jpg');
baners.push('banner3.jpg');
baners.push('banner4.jpg');
baners.push('banner5.jpg');
function swapImage(){
var img = document.getElementById("banner");
img.src = baners[i];
if (i<(baners.length-1)){i++;
}else{
i=0;
}
setTimeout('swapImage()', 2000);
}
function button1 (){
var img = document.getElementById("banner");
img.src = baners[0]
}
I am unsure if it is possible to make one global function for the 5 buttons.
Thank you!
I am unsure if it is possible to make one global function for the 5 buttons.
Yes. Use something like this:
function buttonClicked(number) {
var img = document.getElementById("banner");
img.src = baners[number]
i = number; // set current loop position
}
then call buttonClicked(0) from button1, buttonClicked(1) from button2 and so on. If you want to automatically attach the handlers to the button using a for-loop, check out JavaScript closure inside loops – simple practical example.
Related
I want to get the SRC from every <IMG> in twitter.
let n = document.getElementsByTagName("img");
for(tip of n){
console.log(tip.src);
}
and it works for other pages, but it doesn't for twitter. Finally I did this;
let n = document.getElementsByTagName("img");
function example(){
for(tip of n){
if(tip.src == "https://abs-0.twimg.com/emoji/v2/svg/1f1ea-1f1f8.svg"){
tip.src = "https://abs-0.twimg.com/emoji/v2/svg/1f3f3-fe0f-200d-1f308.svg";
}
}
}
setInterval(example, 100);
With setInterval it works, also, twitter loads stuff dynamically so with setInterval I can get all those new results. (How I could do that without using setInterval?)
Also, for some weird reason, the picture doesn't change. It doesn't update.
Update:
function example(){
let n = document.getElementsByTagName("div");
for(tip of n){
console.log(tip.style['background-image']);
if(tip.style['background-image'] == 'url("https://abs-0.twimg.com/emoji/v2/svg/1f1ea-1f1f8.svg")'){
tip.style['background-image']= 'url("https://abs-0.twimg.com/emoji/v2/svg/1f3f3-fe0f-200d-1f308.svg")';
}
}
}
setInterval(example, 10000);
Now it works perfectly, but how could I get the new data without using setInterval eeeeeeevery time and only call to the function when it's necessary?
You have to load image every time you want to iterate them, to get "fresh" img elements
Try this
function example(){
let n = document.getElementsByTagName("img"); // Moved here
for(tip of n){
if(tip.src == "https://abs-0.twimg.com/emoji/v2/svg/1f1ea-1f1f8.svg"){
tip.src = "https://abs-0.twimg.com/emoji/v2/svg/1f3f3-fe0f-200d-1f308.svg";
}
}
}
setInterval(example, 100);
It is not always that the images are shown with img tag.
If you see some cases on twitter, img tag's sibling is an element with img src in its styles. That element is showing the image. Obviously, this is not the case with every single image on twitter.
But for such a case, you change it's background by
let n = document.getElementsByTagName("img");
for(tip of n){
r.previousSibling.style.backgroundImage='YourImage.png'
}
Also, you have to use some kind of interval to get results that are loaded later. Or you could detect DOM changes using Mutation Observer and only fire your function on DOM change.
I am trying to randomly change background image of a div (#reaction-background) after every click of a button (#angry) with onclick event.
However, the background image only changes once after clicking the button.
HTML:
<div class="btn-list">
<a id="angry">ANGRY</a>
<div id="reaction-background"></div>
Javascript:
// array of pictures
var fileNamesReactions = [
"angry1.jpg",
"angry2.jpg",
"angry3.jpg",
"angry4.jpg",
"angry5.jpg"
];
// random reaction index
var randomIndexReaction = Math.floor(Math.random() * fileNamesReactions.length);
// randomize pictures
document.getElementById("angry").onclick = function() {
document.getElementById("reaction-background").style.background = "url(./img/reactions/angry/" + fileNamesReactions[randomIndexReaction] + ")";
document.getElementById("reaction-background").style.backgroundRepeat = "no-repeat";
document.getElementById("reaction-background").style.backgroundSize = "contain";
}
Your click event handler is, in fact, running every time you click. The problem is that you are only generating a random number once, before any clicks happen and so you set the background image once and further clicks just set the same image over and over.
You need to move the random generator inside of the click callback so that a new random number is generated upon each click.
Also, don't use the onclick property of the element to set up the callback. While this approach works, it's outdated and you should use the more robust and standard .addEventListener() method to set up events.
In addition, do your styling in CSS as much as possible and use CSS classes.
Putting it all together:
// array of pictures
var fileNamesReactions = [
"angry1.jpg",
"angry2.jpg",
"angry3.jpg",
"angry4.jpg",
"angry5.jpg"
];
// Get your DOM references that you'll use repeatedly just once:
let backgroundElement = document.getElementById("reaction-background");
// randomize pictures
document.getElementById("angry").addEventListener("click", function() {
// You have to get a new random each time the click occurs.
var random = Math.floor(Math.random() * fileNamesReactions.length);
backgroundElement.style.background = "url(./img/reactions/angry/" + fileNamesReactions[random] + ")";
console.log(backgroundElement.style.background);
});
/* Use CSS classes as much as possible as they make code much simpler */
#reaction-background {
background-size:"contain";
background-repeat:"no-repeat";
}
<div class="btn-list">
<a id="angry">ANGRY</a>
<div id="reaction-background"></div>
</div>
Move the random number statement inside the onclick method so that it generate a new number on every click. Please find code below:
// array of pictures
var fileNamesReactions = [
"angry1.jpg",
"angry2.jpg",
"angry3.jpg",
"angry4.jpg",
"angry5.jpg"
];
// randomize pictures
document.getElementById("angry").onclick = function() {
// random reaction index
var randomIndexReaction = Math.floor(Math.random() * fileNamesReactions.length);
document.getElementById("reaction-background").style.background = "url(./img/reactions/angry/" + fileNamesReactions[randomIndexReaction] + ")";
document.getElementById("reaction-background").style.backgroundRepeat = "no-repeat";
document.getElementById("reaction-background").style.backgroundSize = "contain";
}
I am currently creating a program which utilizes localStorage to create a site with a wishlist like functionality. However when I go to generate the html page that should create the wishlist with the photo of the item, the name and a button to remove said item from the list. But when I go to assign the onClick functionality to the button, the function fires on page load rather then on click. I have four main java script functions, one to add to the localstorage, one to remove from local storage, a helper function for removing and the one that will generate the wishlist page (where the problem is).
function genWishListPage(){
for (var i = 0; i < localStorage.length; i++) {
var item = getWishlist(i);
var name = document.createElement("p");
var removeButton = document.createElement("button");
var image = document.createElement("img")
image.src = item.image;
removeButton.innerText = "Remove from wishlist";
removeButton.onClick = RemoveFromWishList(item.name);
removeButton.setAttribute("ID","remove");
name.innerText = item.name;
document.body.appendChild(image);
document.body.appendChild(name);
document.body.appendChild(removeButton);
document.body.appendChild(document.createElement("BR"));
//removeButton.setAttribute("onclick", RemoveFromWishList(item.name));
//removeButton.addEventListener('click', RemoveFromWishList(item.name));
//document.getElementById("remove").addEventListener("click",RemoveFromWishList(item.name));
}
}
The commented parts are ways I have already tried and gotten the same bug.
Any help or advice is appreciated.
When you write
removeButton.onClick = RemoveFromWishList(item.name); you are assigning the return value of the function call to the onClick event. Instead you can write
removeButton.onClick = function() { RemoveFromWishList(item.name);}
You should assign a function to the onClick event listener.
I am trying to make an image button on my website toggle wallpaper change frequency options (off,5,10,15,30,30,90 minutes). I have created a custom image for each step (so the user can be aware of the current setting). When implemented the user should be able to repeatedly hit the button to toggle through all 7 options, ultimately looping back to the beginning.
I have some code to swap between two images (below), and have used it for other options on the site (wallpaper on/off), but I just can't figure out a way to get the code to work for my new needs.
if (imageId == 'image1') {
if (document.getElementById) {
var img = document.getElementById(imageId);
img.src = (img.src.indexOf("40_unlocked.jpg") != -1) ? "40_locked.jpg" : "40_unlocked.jpg";
}
}
I expect I will need to determine the current image, then use a switch to advance to the next option, something like the below, but I don't know how to determine the current image - hoping someone can offer a suggestion - thanks in advance!
function changeIt(img) {
var src;
switch (img.id) {
case "example":
src = "n.gif";
break;
case "example2":
src = "n2.gif";
break;
case "example3":
src = "n3.gif";
break;
}
img.src = (img.src.indexOf("jj.gif") < 0 ? "jj.gif" : src);
}
This should get you started
Name your images n0.gif through n6.gif.
toggle.onclick=function(){
//isolate the number of the current image
var num=this.src.split('.gif')[0].split('n')[1]-0;
//add 1 and take mod 7 to loop it back to 0 if it needed
num=++num%7;
//set the src to the new image
this.src='n'+num+'.gif';
}
Try creating an array of all of the src urls & then toggle it like this.
function changeIt(img)
{
var src=img.src;
images=['src1','src2','src3','src4','src5','src6','src7'];
index=images.indexOf(a);
if (index+1>6)
{
index=0;
}
else
{
index+=1;
}
img.setAttribute('src',images[index]);
}
I've tried a lot of things, but nothing is working.
When I click on an mage, I want it's z-index to be "9999". When I click to show another image, I want the previous image's z-index to go back to "0".
So basically, I only want one image to show at a time - I want a specific function to run for each image.
http://jsfiddle.net/WarrenBee/a78R7/
PLEASE help me!
Change your JavaScript to this:
$('.char').click(function () {
$('.char img').css({'z-index' : '0'});
$(this).children('img').css({'z-index' : '9999'});
});
This will set the z-index of all imgs inside a char class back to 0, before setting the one that was clicked to 9999.
Just remember the last image and value and put the old value back:
var lastImage, lastZIndex;
$('.char').click(function () {
var thisImage = $(this).children('img');
if (lastImage) {
lastImage.css('z-index', lastZIndex);
}
lastImage = thisImage;
lastZIndex = thisImage.css('z-index');
thisImage.css({'z-index' : '9999'})
});
Updated fiddle
Ideally, avoid creating global variables by wrapping all of that in a function:
(function() {
var lastImage, lastZIndex;
$('.char').click(function () {
var thisImage = $(this).children('img');
if (lastImage) {
lastImage.css('z-index', lastZIndex);
}
lastImage = thisImage;
lastZIndex = thisImage.css('z-index');
thisImage.css({'z-index' : '9999'})
});
})();
Further updated fiddle