onclick the second time round click - javascript

not sure if this is possible keeping the code simple, but im trying to make it so that i have an image, when you clicked it, it goes to a new image. then when you click that image, it goes back to the original image.
my code is:
function save_data()
{
if ( document.images.save.src == "saved.png") document.images.save.src="save.png";
if (document.images.save.src == "save.png") document.images.save.src="saved.png";
}
<img id="save" onclick="save_data()" src="save.png">

It can be simplified.
Using
<img id="save" onclick="save_data(this)" src="save.png">`
You can do
function save_data(img)
{
img.src = /saved/i.test(img.src) ? 'save.png' : 'saved.png';
}
If this doesn't work, it may have to do with the fact that saved.png is not in the path the html is in. So try it with a full URL:
function save_data(img)
{
var imgpath = 'http://yoursite.com/imgpath/';
img.src = imgpath + (/saved/i.test(img.src) ? 'save.png' : 'saved.png');
}
A note: it may be better to assign the click handler unobtrusively (see also this SO question)

if ( document.images.save.src == "saved.png") - this won't work, because .src returns the full path to the image, not just the filename. For example, http://site.com/path/images/saved.png.
Try matching substrings instead.
function save_data()
{
if ( document.images.save.src.indexOf("saved.png") != -1) document.images.save.src="save.png";
if (document.images.save.src.indexOf("save.png") != -1) document.images.save.src="saved.png";
}

Related

How to change image button on click then get back

I have an image button and I would like to do that if I click to the img button it is changed, then if I click again to the button it change back to the default image.
I have this script but it doesnt change back. Anybody can help me?
<script>
function VOR2(img)
{
if(img.src.match(/blank/))
{
img.src = "VOR.gif";
}
else
{
img.src = "VOR2.gif";
}
}
</script>
<img src="VOR.gif" id="VOR2" onclick=VOR2
The reason that your code is currently not working is because img.src.match(/blank/) looks if the image source has the text "blank" (the forward slashes make it a regex). However neither images you have provided include the text "blank", so it simply does nothing, and isn't the best use case anyways.
The best practice for this would be toggling a class with classList to your image to help identify which "state" it is in, such as the below:
<script>
function VOR2(img) {
isChanged = img.classList.contains('changed-image');
img.src = isChanged ? 'VOR.gif' : 'VOR2.gif';
img.classList.toggle('changed-image');
}
</script>
<img src="VOR.gif" id="VOR2" onclick=VOR2>
I would also suggest moving the script into a different file.
You could do it this way :
JS :
function VOR2(img) {
if (img.src == "VOR2.gif") {
img.src = "VOR.gif";
} else {
img.src = "VOR2.gif";
}
console.log(img.src);
}
HTML :
<img src="VOR.gif" id="VOR2" onclick="VOR2(this)" />

javascript/html: Second onclick attribute

I have an image - image1.png. When I click a button the first time, I want it to change to image2.png. When I click the button for a second time, I want it to change to another image, image3.png.
So far I've got it to change to image2 perfectly, was easy enough. I'm just stuck finding a way to change it a second time.
HTML:
<img id="image" src="image1.png"/>
<button onclick=changeImage()>Click me!</button>
JavaScript:
function changeImage(){
document.getElementById("image").src="image2.png";
}
I'm aware I can change the image source with HTML within the button code, but I believe it'll be cleaner with a JS function. I'm open to all solutions though.
You'll need a counter to bump up the image number. Just set the maxCounter variable to the highest image number you plan to use.
Also, note that this code removes the inline HTML event handler, which is a very outdated way of hooking HTML up to JavaScript. It is not recommended because it actually creates a global wrapper function around your callback code and doesn't follow the W3C DOM Level 2 event handling standards. It also doesn't follow the "separation of concerns" methodology for web development. It's must better to use .addEventListener to hook up your DOM elements to events.
// Wait until the document is fully loaded...,
window.addEventListener("load", function(){
// Now, it's safe to scan the DOM for the elements needed
var b = document.getElementById("btnChange");
var i = document.getElementById("image");
var imgCounter = 2; // Initial value to start with
var maxCounter = 3; // Maximum value used
// Wire the button up to a click event handler:
b.addEventListener("click", function(){
// If we haven't reached the last image yet...
if(imgCounter <= maxCounter){
i.src = "image" + imgCounter + ".png";
console.log(i.src);
imgCounter++;
}
});
}); // End of window.addEventListener()
<img id="image" src="image1.png">
<button id="btnChange">Click me!</button>
For achieve your scenario we have to use of counter flag to assign a next image. so we can go throw it.
We can make it more simple
var cnt=1;
function changeImage(){
cnt++;
document.getElementById("image").src= = "image" + cnt + ".png";
}
try this
function changeImage(){
var img = document.getElementById("image");
img.src = img.src == 'image1.png' ? "image2.png" : "image3.png";
}
Just use an if statement to determine what the image's source currently is, like so:
function changeImage(){
var imageSource = document.getElementById("image").src;
if (imageSource == "image1.png"){
imageSource = "image2.png";
}
else if (imageSource == "image2.png"){
imageSource = "image3.png";
}
else {
imageSource = "image1.png";
}
}
This should make the image rotate between 3 different image files (image1.png, image2.png and image3.png). Bear in mind this will only work if you have a finite number of image files that you want to rotate through, otherwise you'd be better off using counters.
Hope this helps.
Check the below code if you make it as a cyclic:
JS
var imgArray = ["image1.png", "image2.png", "image3.png"];
function changeImage(){
var img = document.getElementById("image").src.split("/"),
src = img[img.length-1];
idx = imgArray.indexOf(src);
if(idx == imgArray.length - 1) {
idx = 0;
}
else{
idx++;
}
document.getElementById("image").src = imgArray[idx];
}
html
<button onclick=changeImage();>Click me!</button>
function changeImage(){
document.getElementById("image").attr("src","image2.png");
}

image not changing on click - javascript

I apologise if it sounds similar to a previous question, but I've gone over those similar questions and I still can't figure out what the problem is with my code. it's petty simple yet it doesn't work.
I have an image. I want it to change to a second image when I click on it, and to a third image when I click on the second image. and then, I want it to change back to the first image when the third image is clicked.
html:
<img id="narrow" class="item" src="images/joe2.jpg" style="cursor:pointer" onclick="changeImage(this);">
javascipt:
function changeImage(imgl) {
if(imgl.src=="images/joe2.jpg") {
imgl.src="images/stray_cat.jpg";
}
else if (imgl.src=="images/stray_cat.jpg") {
imgl.src="images/mathewgarber.jpg";
}
else // (imgl.src=="images/mathewgarber.jpg") {
imgl.src="images/joe2.jpg";
}
}
what happens is that nothing happens when I click on the first image. thanks for your help.
Try something like this:
var images = [
'http://lorempixel.com/100/100/nature/1',
'http://lorempixel.com/100/100/nature/2',
'http://lorempixel.com/100/100/nature/3'
],
i = 0;
function changeImage(img) {
img.src = images[++i % images.length];
}
Comparing image src with a string is not very reliable because it can contain full domain and protocol. Instead you can store images in array and use % operator which is very useful for such kind of cycling.
Demo: http://jsfiddle.net/phJA4/
As dsfq above said, the image src url will be relative, including the site host.
function changeImage(imgl) {
if (imgl.src.indexOf('images/joe2.jpg') > -1) {
imgl.src = "images/stray_cat.jpg";
} else if (imgl.src.indexOf("images/stray_cat.jpg") > -1) {
imgl.src = "images/mathewgarber.jpg";
} else // (imgl.src=="images/mathewgarber.jpg")
{
imgl.src = "images/joe2.jpg";
}
}
If you have your heart set on your method, you can use a indexOf check to determine if the image name is part of the full src url.
First of all you have the last { commented out by your imgl.src=="images/mathewgarber.jpg").
Secondly, the img1.src gives you a different string, take a look at this Demo
You should check for the src like this:
if(imgl.src.indexOf("images/joe2.jpg") > -1)

src image changer after click with JavaScript

I have this image in my html page:
<img src="/images/deactivate.png" onclick="act_deact(this);"/>
and in my javascript code i have this:
function act_deact(image) {
image.src = (image.src=="/images/activate.png" ) ? "/images/deactivate.png" : "/images/activate.png";
}
and when i click on the image that initially deactivated it activate but in the second click it doesn't desactivate !
is there any probleme with my code ?
from JS amateur :)
This is because when you set it to(or it changes to) /images/activate.png on first click, the src attribute is no longer just /images/activate.png but it gets prefixed with the server-address.
You can check it here: http://jsfiddle.net/hGcqq/
Or on your own server, use a console.log or an alert if you prefer.
#hjpotter92 already explained the reason it doesn't work.
One way to make it work is to check if src ends with /images/activate.png:
var activateURL = '/images/activate.png';
if (img.src.substring(img.src.length - activateURL.length) !== activateURL) {
image.src = '/images/activate.png';
} else {
image.src = '/images/deactivate.png';
}
The image.src contains the canonical path, even if initialised with a relative path. You can either use the full path in the condition like
function act_deact(image) {
image.src = (image.src=="FULL-PATH-OF-IMAGE" ) ? "/images/deactivate.png" : "images/activate.png";
}
(to get the full path one may use alert(image.src);)
or, if all your images have unique names
function act_deact(image) {
image.src = image.src.match(/activate.png$/) ? "/images/deactivate.png" : "images/activate.png";
}
The first thing is brackets which should be like this:
image.src = (image.src=="/images/activate.png" ? "/images/deactivate.png" : "/images/activate.png")
Also try image.getAttribute("src") and image.setAttribute("src") instead of image.src.
Please try this code:
function act_deact(image) {
image.setAttribute("src", (image.getAttribute("src")=="/images/activate.png" ? "/images/deactivate.png" : "/images/activate.png"))
}
Edit: other answers tell you about the issue of absolute and relative urls, so getAttribute will fix that issue. I do not recommend to use RegExp or substrings here.
To make it work with relative url you can simply save current url like this:
var newsrc = "/images/deactivate.png";
function act_deact(image) {
if ( newsrc == "/images/deactivate.png" ) {
image.src = "/images/activate.png";
newsrc = "/images/activate.png";
}
else {
image.src = "/images/deactivate.png";
newsrc = "/images/deactivate.png";
}
}
and then call it
<img src="/images/deactivate.png" onclick="act_deact(this);"/>
I found the solution myself :p and i have tried #fardjad proposition that is looking for string in the url and make conditions
i share the solution :)
function act_deact(image) {
if(image.src.indexOf('deactivate') != -1)
image.src="/images/activate.png";
else
image.src="/images/deactivate.png";
}
#hjpotter92: the solution with check condition on image.alt works to:
html:
<img alt="deactivate" src="/images/deactivate.png" onClick="act_deact(this);" />
the Js function :
function act_deact(image) {
if (image.alt=="activate") {
image.src = "/images/deactivate.png";
image.alt = "deactivate" }
else {
image.src = "/images/activate.png";
image.alt = "activate"
}
}
thanks for your responses :)

Changing an image source based on an H1 element in the source code or 'location.path'?

I decided to try a different approach to this problem. Instead of relying on a string I thought it would be more efficient for this specific issue to use the function location.path to determine the source of the album-cover. Here's what I only have so far:
The piece of HTML for the image:
<img src="http://static.last.fm/flatness/catalogue/noimage/noalbum_g3.png" width="220" height="220" class="album-cover"/>
The piece of Javascript I have:
var albumCover = document.getElementsByClassName('album-cover') // Get the album cover
var currentLink = location.pathname
var dictionary =
{ // location.pathname : image source for albumCover
'/music/King+Crimson/Red' : 'http://i1325.photobucket.com/albums/u622/last_fm_projeKct/Last%20FM%20covers/Red.jpg',
'/music/King+Crimson/Discipline' : 'http://i1325.photobucket.com/albums/u622/last_fm_projeKct/Last%20FM%20covers/Discipline.jpg'
}
Now here's the piece of the code that's incomplete:
if (currentLink === ''// first part of the dictionary)
{
albumCover.src = '' second part of the dictionary
};
else{};
Any help is welcome and thanks for reading, cheers.
Old Post:
a follow-up on a question I asked recently but I can't seem to be able to change the code to match what I'm looking for. The code occurs on the following website: link
I'm interested in changing the image source in the code below. However, the new image source is to be determined based on what the H1-element of that webpage contains.
<div class="g3 album-cover-wrapper album-cover-wrapper--no-cover " >
<img src="http://static.last.fm/flatness/catalogue/noimage/noalbum_g3.png" width="220" height="220" class="album-cover"/>
<section class="r add-top-margin remove-bottom-margin">
<div class="g4"> </div>
</section>
</div>
Now I thought it would be useful to use 'dictionary-list' like following:
if H1 contains the string 'Discipline'{img.src="newsource.jpg'};
Thanks for taking the time to read this, cheers!
Edit: here's a piece of code I tried but I'm guessing it needs more info for it to actually work.
var headerDef = document.getElementsByTagName('h1'),
var img = document.getElementsByClassName('album-cover');
if (headerDef === 'Red')
{
img.src = "newsource.jpg";
};
else{};
A few examples of how the list will be:
//string in H1 : new image source for the 'album-cover'-class image
'Discipline' : 'http://ecx.images-amazon.com/images/I/41kcnkbxS-L._SL500_AA300_.jpg',
'Red' : 'http://img.noiset.com/images/album/king-crimson-red-4-cd-cover-31985.gif',
etc...
It's a list for which I'd have to manually add each instance of a page having a specific H1-string.
I'd suggest the following:
var map = {
'red': 'oh my gods!',
'blue': 'blue? Really..?'
};
function influenceImage(source, map) {
if (!source || !map) {
return false;
}
else {
var text = source.textContent || source.innerText;
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word) !== -1) {
return map[word];
}
}
}
}
// in real life, with an image use:
// imageNode.src = influenceImage(document.getElementsByTagName('h1')[0], map);
document.getElementById('test').title = influenceImage(document.getElementsByTagName('h1')[0], map);​
JS Fiddle demo.
In the demo I set the title attribute of an a element, but, of course, as noted in the comment simply set the src attribute of an image node.
The above changed, slightly (within the else {...}, to make it a case-insensitive search/match:
var text = (source.textContent || source.innerText).toLowerCase();
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word.toLowerCase()) !== -1) {
return map[word];
}
}
JS Fiddle demo.
And another edit, again within the else {...}, in order to add a default option in case there's no word-match:
var text = (source.textContent || source.innerText).toLowerCase();
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word.toLowerCase()) !== -1) {
return map[word];
}
}
// we only get here if the `for` loop and the `if` doesn't throw out a match.
return 'default string';
JS Fiddle demo.

Categories