Toggle image source with jQuery - javascript

I want to do something interesting, so for example i have an image on my website and i want to change it when a button is triggered, but then i want to revert it back to the original when the button is clicked again (or add the same img to it) and repeat this all the time when the event is clicked. How can I achieve this ?
Here is my current Jquery but only that works for one time click
$('#menu-btn').on({
'click': function () {
$('#div1').attr('src', 'images/card-light.png');
}
});
Html code
<button id="menu-btn">click me</button>
<img id="div1" src="./images/card-dark.png">
Assets
images/card-dark.png
images/card-light.png

On document load, store the image source in a variable. In our case, it's called prev.
Inside the toggle function, we check whether the source of the image is equal to the source when it was loaded. If it was, we change the source to another image. When the source is changed and we call the toggle function again, we know that the source is different from the previous one, so we revert it back to the original source.
$(document).ready(function() {
var img = $('#img');
var prev = img[0].src;
function toggle(img) {
let src = img.src;
if (src == prev) {
img.src = "https://pbs.twimg.com/profile_images/453956388851445761/8BKnRUXg_400x400.png";
img.height="48";
} else {
img.src = prev;
}
}
$('button').on('click', function() {
toggle(img[0]);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" height="48"></script>
<img id="img" src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1">
<button>Toggle</button>
We can take it a step further by using data attributes to store the two sources so you can easily extend this for multiple images.
$(document).ready(function() {
var img = $('#img');
var prev = img[0].src;
function toggle(i) {
let src = i[0].src;
let dsrc = i.data('switch-with');
if(dsrc==src){
i[0].src=prev;
}else{
i[0].src=dsrc;
i[0].height="48";
}
}
$('button').on('click', function() {
toggle(img);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" height="48"></script>
<img id="img" src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1" data-switch-with="https://pbs.twimg.com/profile_images/453956388851445761/8BKnRUXg_400x400.png">
<button>Toggle</button>

Related

Load content in div from a href tag in jQuery

I want to load all images before displaying them in a slideshow. I have been searching a lot but nothing seems to work. This is what i have so far and it doesn't work. I am loading images from the <a> tag from another div.
$('.slideshow').load(function(){
if (loaded<length){
first = $(settings.thumb).eq(loaded).find('a').attr("href");
$('<img src="'+first1+'"/>').appendTo('.slideshow');
}
else{ $('.slideshow').show(); }
loaded++;
});
Add an event listener to each image to respond to when the browser has finished loading the image, then append it to your slideshow.
var $images = $("#div_containing_images img");
var numImages = $images.length;
var numLoaded = 0;
var $slideshow = $(".slideshow");
$images.each(function() {
var $thisImg = $(this);
$thisImg.on("load", function() {
$thisImg.detach().appendTo($slideshow);
numLoaded++;
if (numLoaded == numImages) {
$slideshow.show();
}
});
});
It's a good idea to also listen for the error event as well, in case the image fails to load. That way you can increase numLoaded to account for broken image. Otherwise, your slideshow will never be shown in the event the image is broken.
Also note, that by calling detach() followed by appendTo() I am am moving the image in the DOM. If instead, you want to copy the image, use clone() instead of detach().
* EDIT TO MODIFY USER'S EXACT USE CASE *
var $images = $("li.one_photo a");
var numImages = $images.length;
var numLoaded = 0;
$images.each(function() {
$('<img />',
{ src: $(this).attr("href") })
.appendTo('.slideshow')
.on("load error", function() {
numLoaded++;
if(numLoaded == numImages) {
$('.slideshow').show();
}
});
});
* EDIT #2 *
Just realized you were putting everything in the $(".slideshow").load() function. Since $(".slideshow") represents a DIV, it will never raise a load event, and the corresponding function will never execute. Edited above accordingly.

hovering over image changes it to hoverimg. but after clicking the image, hover stops working

It works but there's a pesky bug I can't understand how to fix (i'm a beginner).
What happens is there are 3 image buttons (only showing code for 1 here) and when i hover over them, they change image, and revert when i take mouse off. This is the html.
When I click any of the 3 image buttons (javascript), it changes its own image, and sets the other 2 image buttons to the normal image.
After this point (clicking the image) the hovering html code doesn't work anymore.
function changeImage3() {
document.getElementById('MageBTN').src = 'images/Character/NotSelected_Mage.png';
document.getElementById('WarriorBTN').src = 'images/Character/NotSelected_Warrior.png';
}
<a href="#" onclick="changeImage3()"><img id="RogueBTN" src="images/Character/NotSelected_Rogue.png" alt="image"
onclick="this.src='images/Character/Selected_Rogue.png';
this.onmouseover = false; this.onmouseout = false;"
onmouseover="this.src='images/Character/Selected_Rogue.png';"
onmouseout="this.src='images/Character/NotSelected_Rogue.png';">
</a>
just suggestion.. Use simple css property..
#yourID a:hover{
//your image which want to show on hover
}
If I have understand correctly you want to lock the selected state of a button on click and unlock/reset to not-selected when another button is clicked. Therefore you have to store the state of the buttons so I suggest to move all functionality to a script. Since you have all images well ordered it's enough to change Sel/NotSel in the url.
window.onload = function() { // ensures that all elements are there
var buttons = {
RougeBTN: document.getElementById("RougeBTN"),
VertBTN: document.getElementById("VertBTN"),
BleuBTN: document.getElementById("BleuBTN")
},
locked;
function clicked() {
for (var btn in buttons) { // iterate over the buttons
var b = buttons[btn];
// if this button was clicked save the state
if (btn == b.id) locked = btn;
else {
b.src = b.src.replace('/Sel', '/NotSel');
}
}
}
function mover() { // works only when button is not locked
if (locked != this.id) this.src = this.src.replace('/NotSel', '/Sel');
}
function mout() { // works only when button is not locked
if (locked != this.id) this.src = this.src.replace('/Sel', '/NotSel');
}
for (var btn in buttons) { // now set the functions to all buttons
var b = buttons[btn];
b.onclick = clicked; b.onmouseover = mover; b.onmouseout = mout;
}
}
In html all buttons look like this:
<img id="RougeBTN" src="images/Character/NotSelected_Rouge.png" alt="image">

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();
}

Javascript - swap image on click or rollover

I know how to do this in jquery but i am trying to do the below in pure old school javascript. Can someone help:
$(".thumbnail").click(function() {
$("#mainImage").attr("src", $(this).attr("src"));
});
My ultimate goal is to click on a thumbnail and have the main image change but I need to do it in javascript (no jquery). I know this sounds pretty simple but I cannot figure it out. thank you.
There are so many things that jQuery gives you automatically that it's difficult to give you an answer that will do everything that your jQuery code does. Here is a simple example that will find every image with a class of thumbnail and set its onclick property to an event handler that performs an image swap.
onload = function () {
var bigImg = document.getElementById("mainImage");
for (var i = 0; i < document.images.length; i++) {
var img = document.images[i];
if (/\bthumbnail\b/.test(img.className) {
img.onclick = thumbnailHandler;
}
}
function thumbnailHandler(e) {
bigImg.src = this.src;
}
};
If you don't have to support IE7, you can simplify it slightly by using document.querySelectorAll():
onload = function () {
var bigImg = document.getElementById("mainImage");
var thumbs = document.querySelectorAll(".thumbnail");
for (var i = 0; i < thumbs.length; i++) {
thumbs[i].onclick = thumbnailHandler;
}
function thumbnailHandler(e) {
bigImg.src = this.src;
}
};
As an aside, I don't understand why you are setting the source of the main image to be the source of the thumbnail. Are you loading the full image into the thumbnail? That can be a lot to download and can quickly increase the memory footprint of your page.
Event delegation is probably the easiest way:
function expandThumbnail(e) {
if(~(' ' + e.target.className + ' ').indexOf(' thumbnail ')) {
document.getElementById('mainImage').src = e.target.src;
}
}
if(document.addEventListener) {
document.addEventListener('click', expandThumbnail, false);
} else {
document.attachEvent('onclick', function() {
expandThumbnail({
target: event.srcElement
});
});
}
If I understand right, you have a thumbnail image displayed, let's say '1thumb.png', of an associated image, let's say '1.png', and when you click this thumbnail image you want to change the src attribute of a main image, let's say with id='mainimg', to show the '1.png' image associated to the thumbnail instead of whatever it's showing. I tried this and it works:
Inside your <header>:
<script type='text/javascript'>
function myHandler(source){
document.getElementById('mainimg').src=source;
}
</script>
...
Your thumbnail code:
<img src='1thumb.png' onclick="myHandler('1.png')"/>
or, for rollover triggering:
<img src='1thumb.png' onmouseover="myHandler('1.png')"/>
Check it out: http://jsfiddle.net/d7Q27/7/

Javascript: onmouseover function

I have a problem with changing onmouseover and onmouseout attributes on dynamic pictures. The way i want it to work is whenever i put my mouse over images the images must change and when i take my mouse away it must be changed to the original picture. and whenever i select any image, that image must be changed to the image which was displayed while moving the mouse across the image. and when i select any other image the same process must take place but the previous image that was changed must be changed back to the original picture.
I have accomplished all of the above but my problem is when i select multiple pictures and put my mouse over images that were previously selected, those images do not change (onmouseover attribute does not work on them anymore).
<script language="javascript">
function changeleft(loca){
var od=''
var imgs = document.getElementById("leftsec").getElementsByTagName("img");
for (var i = 0, l = imgs.length; i < l; i++) {
od=imgs[i].id;
if(od==loca){
imgs[i].src="images/"+od+"_over.gif";
imgs[i].onmouseover="";
imgs[i].onmouseout="";
}else{
od = imgs[i].id;
imgs[i].src="images/"+od+".gif";
this.onmouseover = function (){this.src="images/"+od+"_over.gif";};
this.onmouseout = function (){this.src="images/"+od+".gif";};
}
}
}
</script>
<div class="leftsec" id="leftsec" >
<img id='wits' class="wits1" src="images/wits.gif" onmouseover="this.src='images/wits_over.gif'" onmouseout="this.src='images/wits.gif'" onclick="changeleft(this.id)" /><br />
<img id='city' class="city1" src="images/city.gif" onmouseover="this.src='images/city_over.gif'" onmouseout="this.src='images/city.gif'" onclick="changeleft(this.id)" /><br />
<img id='organise' class="city1" src="images/organise.gif" onmouseover="this.src='images/organise_over.gif'" onmouseout="this.src='images/organise.gif'" onclick="changeleft(this.id)" /><br />
<img id='people' class="city1" src="images/people.gif" onmouseover="this.src='images/people_over.gif'" onmouseout="this.src='images/people.gif'" onclick="changeleft(this.id)" /><br />
</div>
I would recommend to use an Ajax library (jQuery, YUI, dojo, ExtJS, ...). In jQuery I would do something like:
Edit: Extended the example with .click() ability.
var ignoreAttrName = 'data-ignore';
var imgTags = jQuery('#leftsec img'); // Select all img tags from the div with id 'leftsec'
jQuery(imgTags)
.attr(ignoreAttrName , 'false') // Supplying an ignore attribute to the img tag
.on('click', function () {
jQuery(imgTags).attr(ignoreAttrName, 'false'); // Resetting the data tag
jQuery(this).attr(ignoreAttrName, 'true'); // only the current will be ignored
// Do whatever you want on click ...
})
.on('mouseover', function () {
// This will be called with the img dom node as the context
var me = jQuery(this);
if (me.attr(ignoreAttrName) === 'false') {
me.attr('src', me.attr('id') + '.gif');
}
})
.on('mouseout', function () {
// This will be called when leaving the img node
var me = jQuery(this);
if (me.attr(ignoreAttrName) === 'false') {
me.attr('src', me.attr('id') + '-over.gif');
}
});
With a library it's cleaner and more scalable I think and the chance that it's working in other browsers is increased too :).
Hope this helps you out!

Categories

Resources