How can I swap between two images on infinite clicks? - javascript

How can I swap between two images on infinite clicks (not once) using JS or jQuery
$("button").click(function(){
$("img").attr("src","The New SRC");
});
This code works, but just once.

Try this
var q = 0;
function swapImage() {
if (q == 0) {
document.getElementById("image").setAttribute('src', 'https://images.unsplash.com/photo-1562102010-558d6be6268e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
q++;
} else {
document.getElementById("image").setAttribute('src', 'https://images.unsplash.com/photo-1567095740613-beef70b7e61c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
q--;
}
}
<img id="image" src="https://images.unsplash.com/photo-1567095740613-beef70b7e61c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" onclick="swapImage();" />

Let make this simple as possible swap the src and data-src on click.
$('.changeSrc').on('click', function(e){
let src2= $('#img').data('src2');
$('#img').data('src2', $('#img').attr('src'));
alert(src2);
$('#img').attr('src', src2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="img" src="./images/img1.jpg" data-src2="./images/img2.jpg"/>
<button class="changeSrc">Change Picture</button>

If by "forever" you mean your user will always see the same image once he's changed it, you need to store that information somewhere. Here's an example where you store the image source in the browser's local storage and read that to set the src property of the image element:
<p>
<img id="my-img" src="">
</p>
<button onclick="changeImage()">
Change image
</button>
<script>
const myImg = document.getElementById("my-img")
const googleLogo = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"
const duckduckgoLogo = "https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png"
const changeImage = () => {
if(myImg.src === googleLogo) {
myImg.src = duckduckgoLogo
localStorage.setItem("img-src", duckduckgoLogo)
} else {
myImg.src = googleLogo
localStorage.setItem("img-src", googleLogo)
}
}
const getImageSrc = () => {
const loadedSrc = localStorage.getItem("img-src")
if(loadedSrc == null) {
myImg.src = googleLogo
} else {
myImg.src = loadedSrc
}
}
getImageSrc()
</script>
Note: The code is correct but it doesn't work in the snippet because I'm reading from localStorage and this seems to be not allowed inside a snippet.

Related

How to toggle between two images with a button using Javascript code?

I have an HTML document that has an image, and I want to click a button to
toggle between the color version and the black & white version. My
javascript code is as follows is below. I realize this question has been
answered before, but the answers were unclear. Questions: Is the IF condition valid? If not, what can I use? Can one compare an image.src with an address on my computer as typed below? Note that nothing is changing when I click. The color image remains.
let colorImage = document.getElementById("colorImage");
let button2 = document.getElementById("button2");
function changeToBW() {
if (colorImage.src == "Rondout.jpg") { // I tried three === but that
// didn't work either.
colorImage.src = "Rondout(B&W).jpg";
}
else {
colorImage.src = "Rondout.jpg";
}
}
button2.addEventListener("click", changeToBW);
A portion of my HTML code that's within the body below:
<img id = "colorImage" class = "image" src = "Rondout.jpg">
<button id = "button2" type = "button">Change to B&W</button>
I copied your code to see where the problem is. I used 2 imgs that i just downloaded form google: img1.png and img2.jpeg
It didn't worked. So I opened the DevTab of Google Chrome.
So my code:
let colorImage = document.getElementById("colorImage");
let button2 = document.getElementById("button2");
function changeToBW() {
if (colorImage.src == "img1.png") { // colorImage.src = file:///D:/Kokal/Code/JsTests/img1.png
colorImage.src = "img2.jpeg";
}
else {
colorImage.src = "img1.png";
}
}
button2.addEventListener("click", changeToBW);
The problem is that colorImage.src holds the absolute path to the file. So you never end-up in the if you aways go in the else.
Also you want to change the attribute src not the property. So you need to read the attr too. The way to do it is with the function getAttribute('src') on the colorImage.
After that you will need to set that attr with setAttribute('src', [new value])
If something is not clear chek my code below.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<img id = "colorImage" class = "image" src = "./img1.png">
<button id = "button2" type = "button">Change to B&W</button>
<script src="app.js" type="text/javascript"></script>
</body>
</html>
JS:
let colorImage = document.getElementById("colorImage");
let button2 = document.getElementById("button2");
function changeToBW() {
if (colorImage.getAttribute('src') === "./img1.png") {
colorImage.setAttribute('src', "./img2.jpg");
}
else {
colorImage.setAttribute('src', "./img1.png");
}
}
button2.addEventListener("click", changeToBW);
You can use the data attribute to keep track of which image is displayed.
In my example, I use the data attribute data-color for this.
Then in the onClick handler, I get the data-color value and toggle between the 0 and 1. The 1 and 0 then correspond with the index in the array images. Which is added to the src of colorImage.
Here's a working example.
let colorImage = document.getElementById("colorImage");
let button2 = document.getElementById("button2");
function changeToBW() {
var images = [
"https://images.pexels.com/photos/57905/pexels-photo-57905.jpeg",
"https://images.pexels.com/photos/56866/garden-rose-red-pink-56866.jpeg"
];
var imageNum = parseInt(colorImage.dataset.color);
var nextImg = imageNum === 0 ? 1 : 0;
colorImage.src = images[nextImg];
colorImage.dataset.color = nextImg;
}
button2.addEventListener("click", changeToBW);
<img id="colorImage" data-color="0" class="image" src="https://images.pexels.com/photos/57905/pexels-photo-57905.jpeg" width="200">
<div><button id="button2" type="button">Change to B&W</button></div>
let colorImage = document.getElementById("colorImage");
let button2 = document.getElementById("button2");
let imgFlag = 1;
function changeToBW() {
if (imgFlag) {
colorImage.setAttribute('src', "./img2.jpg");
ImgFlag = 0;
}
else {
colorImage.setAttribute('src', "./img1.png");
ImgFlag = 1;
}
}
button2.addEventListener("toggle", changeToBW);

Execute js after all image loaded

(I searched, but not find exactly/easy solution)
I'm trying to execute JS after all images completely loaded. My goal is, when all images finish load completely, then removeClass my-loader and addClass visible to main-slider div.
HTML:
<div class='main-slider my-loader'>
<img src="/nice-girl.jpg">
<img src="/nice-car.jpg">
<img src="/nice-boy.jpg">
</div>
Execute below js when all images completely loaded
$(".main-slider").removeClass("my-loader").addClass("visible");
Tried :
But not work, problem is it execute before complete image load:
var imagesPre = new Array;
var success = new Array;
$('.big-slides img').each(function(){
imagesPre.push(this.src);
});
for (i = 0; i < imagesPre.length; i++) {
(function(path, success) {
image = new Image();
image.onload = function() {
success.resolve();
};
image.src = path;
})(imagesPre[i], success[i] = $.Deferred());
}
$.when.apply($, success).done(function() {
$(".main-slider").removeClass("my-loader").addClass("visible");
});
Any ideia for simple solution?
You can use load() to check if the images are loaded!
$('.imgTag').each(function(){
$(this).load(function(){
$(".main-slider").removeClass("my-loader").addClass("visible");
})
})
This may not work sometimes when the images are cached by the browser. Please check Caveats of the load event when used with images
var img = $('img')
var count = 0
img.each(function(){
$(this).load(function(){
count = count + 1
if(count === img.length) {
$('.main-slider').removeClass('my-loader').addClass('visible')
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='main-slider my-loader'>
<img src="https://unsplash.it/200/300/?random">
<img src="https://unsplash.it/200/300/?random">
<img src="https://unsplash.it/200/300/?random">
</div>
But, this answer is a working case.
<div class='main-slider my-loader'>
<img class="imgTag" src="/nice-girl.jpg">
<img class="imgTag" src="/nice-car.jpg">
<img class="imgTag" src="/nice-boy.jpg">
</div>
jquery codes:
`
window.loadCount = 0;
$('.imgTag').onload(function(){
window.loadCount++;
if(window.loadCount == $('.imgTag').length){
$('.imgTag').show();
}
});
`

Toggle image src attribute using Javascript

I am trying to change the HTML image src using Javascript. I have two images Plus.gif and Minus.gif.I have inserted HTML img tag and have written a Javascript function to change the image src when clicked.
Problem is that I want to change it back again when user clicks on the image.
For example when the page is loaded the Plus.gif shows and when user clicks on it the image it changes to Minus.gif.
I want it so, when the image is Minus.gif and user clicks on it this should be changed to Plus.gif.
Here is my Javascript function:
<script language="javascript" type="text/javascript">
function chngimg() {
var img = document.getElementById('imgplus').src; //= 'Images/Minus.gif';
if (img) {
document.getElementById('imgplus').src = 'Images/Minus.gif';
} else if (!img) {
document.getElementById('imgplus').src = 'Images/Plus.gif';
alert(img);
}
}
</script>
Image tag:
<img id="imgplus" alt="" src="Images/Plus.gif" onmouseover="this.style.cursor='pointer'" onclick="chngimg()" />
See the changes I made to make it working
<script language="javascript" type="text/javascript">
function chngimg() {
var img = document.getElementById('imgplus').src;
if (img.indexOf('Plus.gif')!=-1) {
document.getElementById('imgplus').src = 'Images/Minus.gif';
}
else {
document.getElementById('imgplus').src = 'Images/Plus.gif';
}
}
</script>
<img id="imgplus" alt="" src="Images/Plus.gif" onmouseover="this.style.cursor='pointer'" onclick="chngimg()" />
Hope that resolves your question.
One way would be to add a toggle variable in your function:
var toggle = false;
function chngimg() {
if (toggle === true) {
document.getElementById('imgplus').src = 'Images/Minus.gif';
} else {
document.getElementById('imgplus').src = 'Images/Plus.gif';
alert(img);
}
toggle = !toggle;
}
Note that it's a better practice to use a sprite for this kind of thing. If you're using two images, the user experience is going to be clunky, because the first time they click the image, there will be a slight delay while the second image loads.
Ideally you would have the two images as a sprite sheet, and be using JQuery. Then you could just do it like this.
HTML
<img id="imgplus" src="Images/Sprite.gif" onclick="chngimg()" />
CSS
#imgplus .clicked { background-position: 0 -30px; }
Javascript
function chngimg() {
$("#imgplus").toggleClass("clicked");
}
I have successfully used this general solution in pure JS for the problem of toggling an img url:
function toggleImg() {
let initialImg = document.getElementById("img-toggle").src;
let srcTest = initialImg.includes('initial/img/url');
let newImg = {
'true':'second/img/url',
'false':'initial/img/url'}[srcTest];
return newImg;
}
Then call toggleImg() inside whatever event handler you use....
someButton.addEventListener("click", function() {
document.getElementById("img-toggle").src = toggleImg();
}

How do I exchange two images in a webpage (on two consecutive clicks) using jQuery?

I have two images among many that I want to swap places between. If I click on one image, then the other, the respective images should swap with each other and the rest should remain the same. I'm a beginner at this so any help or direction would be helpful.
This works also for every image:
<img src="http://stunningwebsitetemplates.files.wordpress.com/2011/12/jquery.png"/>
<img src="http://bloggerschmidt.de/images/stories/logo-mootools.gif" />
<img src="http://stunningwebsitetemplates.files.wordpress.com/2011/12/jquery.png"/>
<img src="http://bloggerschmidt.de/images/stories/logo-mootools.gif" />
JS
$(function(){
var src="";
var old;
$("img").click(function(){
if(src=="")
{
src=$(this).attr("src");
old=$(this);
}
else
{
old.attr("src",$(this).attr("src"));
$(this).attr("src",src);
src="";
}
});
});​
Another solution without any global variable.
html
<div id="images">
<img scr="/images/1.jpg" />
<img scr="/images/2.jpg" />
<img scr="/images/3.jpg" />
<img scr="/images/4.jpg" />
<img scr="/images/5.jpg" />
</div>
Js file
$('img').click(function(){
if($('#images img').hasClass('selected')){
var src = $(this).attr('src');
$('.selected').attr('src',src);
$(this).attr('src',$('.selected').attr('src'));
$(this).removeClass('selected');
}
else
$(this).addClass('selected');
});
Here is a different approach that swaps the actual elements rather than the src of the img, also avoids using external variables for the swap.
$('img.swap').on('click', function() {
var t = $(this);
if (t.hasClass('clicked')) {
t.removeClass('clicked');
return;
}
var clicked = $('img.swap.clicked')
if (clicked.length === 0) {
t.addClass('clicked');
return;
}
var placeHolder = $('<div id="placeholder"></div>');
clicked.before(placeHolder);
t.after(clicked);
placeHolder.before(t).remove();
clicked.removeClass('clicked');
});​
Example - http://jsfiddle.net/BxST9/3/ (using div instead of img but shouldn't make a difference)
See the example on: http://jsfiddle.net/Lvp4j/1/
var selected;
$("img").click(
function() {
if (!selected)
{
selected = this;
$(selected).addClass("selected");
}
else
{
var src1 = $(selected).attr("src");
var src2 = $(this).attr("src");
$(this).attr("src", src1);
$(selected).attr("src", src2);
$(selected).removeClass("selected");
selected = null;
}
}
);
My code adds also a selected class so you can highlight the clicked image...
try below code
html
<div>
<img scr="/images/1.jpg" />
<img scr="/images/2.jpg" />
<img scr="/images/3.jpg" />
<img scr="/images/4.jpg" />
<img scr="/images/5.jpg" />
</div>
Js file
(function() {
var swapArray = [];
var count=0;
$('img').click(function(){
count++;
swapArray.push($(this).attr('src'));
$(this).addClass(count);
if(count==2){
$('.1').attr('src',swapArray[1]).removeClass('1');
$('.2').attr('src',swapArray[0]).removeClass('2');
swapArray.length = 0;
count=0;
}
});
}());​
Given this HTML:
<img src="image_1.jpg" />
<img src="image_2.jpg" />
<img src="image_3.jpg" />
<img src="image_4.jpg" />
You could use the following JavaScript:
(function() {
var previous = null;
$('img').click(function() {
var current = $(this);
if (current.is(previous)) { // clicked same image twice; reset
reset_clicked();
} else if (previous != null) { // two images clicked; swap
swap_src(previous, current);
reset_clicked();
} else {
set_clicked(current);
}
});
function reset_clicked() {
previous.removeClass('clicked');
previous = null;
}
function set_clicked(img) {
img.addClass('clicked');
previous = img;
}
function swap_src(img1, img2) {
var src1 = img1.attr('src');
img1.attr('src', img2.attr('src'));
img2.attr('src', src1);
}
}());​
The 'clicked' class is added purely so you can use CSS to style clicked images. This class could also be used to identify any previously-clicked images, but I've used a JavaScript variable instead because that's quicker than a DOM lookup.
There's a demo on JSFiddle: jsfiddle.net/cvthL/2
This answer was posted as an improved version of Jitendra Pancholi's first answer and an alternative to his/her second answer.

Image-loaded-show function by javascript in mobile browser

I'am using the following javascript code to implement image-loaded-show function in mobile web browser (supporting HTML5). Image-loaded-show means that before the image is completely loaded, the width and height is 0, namely it willn't show and occupy any space.
Now the problem is that the images will not show until all the images are loaded.
What I need is that the iamge in the page is seperate, once loaded, the image show up.
Any tips on how to modify this javascript code? thanks.
<script type='text/javascript'>
var srcs = [];
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
}
var content = document.getElementById('content');
var images = content.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
srcs[i] = images[i].src;
loadImage(images[i], srcs[i],
function (cur, img, cached) {
cur.src = img.src;},
function (cur, img) {
cur.style.display = 'none';});
}
};
var loadImage = function (cur, url, callback, onerror) {
var img = new Image();
img.src = url;
img.width = '100%';
if (img.complete) {
callback && callback(cur, img, true);
return;
}
img.onload = function () {
callback && callback(cur, img, true);
return;
};
if (typeof onerror == 'function') {
img.onerror = function () {
onerror && onerror(cur, img);
}
}
};
</script>
The source code of the page is :
<body onload="doBindLinks();"><div id="content"> images and text </div></body>
P.S: Because I need to write this javascript string in C#, I replace the (") into (').
Edited:
Is the following right:
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
elem.setAttribute('display','none');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
elem.attachEvent('onload',onImageLoaded);
}
};
window.onImageLoaded = function() {
var elem = event.srcElement;
if ( elem != null ) {
elem.setAttribute('display','block');
}
return false;
};
Besides, the css code is:
img {width: 100%; border-style:none;text-align:center;}
But the images still wouldn't show until all are loaded.
I'm not 100% sure I understand your question. Are you trying to hide the image until it is fully loaded? Are you writing the images out to the page, or are they already in the page? Here are a couple of options:
set style="display:none". Then add onload="this.style.display='';" event listener to image.
images will each show as they are loaded.
if you are able to change the c# code, then simply write all the image urls out as a list of strings into an imageload function. Then use this function to create the images and add them to the content div.
I hope this helps you. If not, please provide more context, and I will try to help farther.
Ok, I see where you are going now. You can take out all that javascript that you have written. Maybe print it out so that you can throw it in the trash. Then take my example here... and it will do the trick for you. each image shown only as it is loaded. Obviously if you want to change any other properties you can do it in the showImage function. hope this helps.
<html>
<head>
<style>
img{display:none;}
</style>
<script type="text/javascript">
function showImage(elem) {
elem.style.display = 'block';
}
</script>
</head>
<body><div id="content">
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
</dvi>
</body>
</html>

Categories

Resources