1

I'm changing the img src on click using javascript.

I'm trying to determine whether to switch on or off.

I'm testing the following:

var img_el = document.getElementById("on_off_img");
if ( img_el.src == 'img/on.png' ) {

  img_el.src = 'img/off.png'
} else {

  img_el.src = 'img/on.png'
}

My problem is that i never get a match - it looks like img_el.src returns the full URL... Is there a function to just test the actual filename instead of the full string to the file?

Or is there a better way to manage the click?

5 Answers 5

5

use indexOf() instead of comparing the src

e.g

var img_el = document.getElementById("on_off_img");
if ( img_el.src.indexOf('on.png') > -1) {
  img_el.src = 'img/off.png'
} else {

  img_el.src = 'img/on.png'
}
Sign up to request clarification or add additional context in comments.

Comments

2

Yuo can always use indexOf:

if(img_el.src.indexOf('img/on.png') > -1){
  img_el.src = 'img/off.png'
}else{
  img_el.src = 'img/on.png'
}

Comments

1

To shorten this even more, you can use a ternary operator:

var img_el = document.getElementById("on_off_img"),
    isOn   = img_el.src.indexOf('on.png')>-1;
img_el.src = isOn ? 'img/off.png' : 'img/on.png';

Comments

1

You can use match statement aswell.

var img_el = document.getElementById("on_off_img");
if ( img_el.src.match("on.png")) 
{
  img_el.src = 'img/off.png'
} else 
{
  img_el.src = 'img/on.png'
}

Comments

0

Try using JQuery:

$("#on_off_img").click(function(){
    if($(this)[0].nameProp == "on.png")
        $(this).attr("src","img/off.png");
    else
        $(this).attr("src","img/on.png");         
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.