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?

php-b-grader
  • 2,876
  • 10
  • 37
  • 50

5 Answers5

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'
}
Chris Marais
  • 411
  • 2
  • 10
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'
}
tcooc
  • 18,644
  • 3
  • 34
  • 53
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'
}
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';
Community
  • 1
  • 1
KooiInc
  • 104,388
  • 28
  • 131
  • 164
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");         
});
Sukhjeevan
  • 3,288
  • 7
  • 41
  • 84