Toggle image src attribute using Javascript - 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();
}

Related

Toggle image source with jQuery

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>

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">

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!

Toggling between two images by clicking

Due to this link
I changed it to this one:
<html>
<head>
<script>
var toggleimage=new Array("p1.gif","p.gif")
//do not edit the variables below
var image_1=new Image()
var image_2=new Image()
image_1.src=toggleimage[0]
image_2.src=toggleimage[1]
var i_image=0
function testloading() {
isloaded=true
}
function toggle() {
if (isloaded) {
document.togglepicture.src=toggleimage[i_image]
}
i_image++
if (i_image>1) {i_image=0}
}
onload=testloading
</script>
<title>
</title>
<meta content="">
<style></style>
</head>
<body>
<img name="togglepicture" src="p1.gif" border="0">
</body>
</html>
when I click on the image p it will show me p1 and vice versa
Now I have problem image has a name:
<img name="togglepicture" src="p1.gif" border="0">
and it will get the name here:
document.togglepicture.src=toggleimage[i_image]
I want to have many images so I thaught I need to change the togglepicture to a variable
for example:
function toggle(a) {
if (isloaded) {
document.a.src=toggleimage[i_image]
}
i_image++
if (i_image>1) {i_image=0}
}
and for input forexample it will be toggle('nameofimage') and in the href it will be something like
<a href="javascript:toggle('pic1')">
I wasn't successful.How can I use this function when I have more than a picture to click?
I made a modular toogle, visible here: http://jsfiddle.net/Regisc/N7bgz/2/
Usage sample:
<img id="image1" src="http://dummyimage.com/50/f00/fff&text=a"
onclick='toogle(this, ["http://dummyimage.com/50/ab0/fff&text=b",
"http://dummyimage.com/50/ab0/fff&text=c"]);' />
you can't use
document.a.src=toggleimage[i_image];
instead use
document.getElementById(a).src=toggleimage[i_image];
And you also need to add an id to your img element.
Something like the following should work for any number of images provided toggleimage is a contiguous array.
var toggleimage = ["p1.gif","p.gif"];
var toggle = (function() {
var count = 0;
var len = toggleimage.length;
var el = document.getElementsByName('togglepicture')[0]
return function() {
if (isloaded) {
el.src = toggleimage[count++ % len];
}
};
}());
I'm not entirely sure I got your question. Are you asking:
How to edit the function to allow toggling between more than just two images, or
How to edit the function to handle more than one set of toggle images?
Toggling between more than just two images
var toggleimage=new Array("p1.gif","p.gif","p2.gif","p3.gif","p4.gif")
var totalImages=4;
function toggle() {
if (isloaded) {
document.togglepicture.src=toggleimage[i_image]
}
i_image++
if (i_image>totalImages) {i_image=0}
}
How to edit the function to handle more than one set of toggle images?
call the JS function like this
<a href="javascript:toggle(this)">
And, in your JS function,
var id = div.id;
Use this in an if-else to determine which control called the function and accordingly which array of images to use.
function toggle(div)
{
var id = div.id;
if (isloaded)
{
if (id == 'myFirstToggleImageControl')
{
document.togglepicture.src=toggleimage[i_image];
}
else if (id == 'mySecondToggleImageControl')
{
document.togglepicture.src=toggleimageSource2[i_image];
}
}
i_image++
if (i_image>1) {i_image=0}
}
Note: You will want to use an independent counter for the second control. So, possibly i_image1 and i_image2
<html>
<head>
<script>
// images list (properties name must by equal to id of IMAGE html element)
var imageList={
image1: {
currentIndex:0,
images:["p1.gif","p.gif"]
}
};
// preloading images using closure (additionaly replace image URL's with image objects)
(function() {
for(var p in imageList)if(imageList.hasOwnProperty(p)) {
for(var i=0;i<imageList[p].images.length;i++) {
var img=new Image(),src=imageList[p].images[i];
(imageList[p].images[i]=img).src=src;
}
}
})();
function toogleImage() {
var info=imageList[this.id];
info.currentIndex++;
if(info.currentIndex===info.images.length)info.currentIndex=0;
this.src=info.images[info.currentIndex].src;
}
// setting start images
window.onload=function() {
for(var p in imageList)if(imageList.hasOwnProperty(p)) {
//try{
document.getElementById(p).src=imageList[p].images[0].src;
//}
//catch(ex){}
}
}
</script>
</head>
<body>
<img id="image1" onclick="toogleImage.call(this);"/>
</body>
</html>
http://jsfiddle.net/X4Q2m/

Categories

Resources