Zachary
Zachary

Reputation: 65

JavaScript element src change

So I have two images, "safety-pin-green" and "safety-pin-blue" and I want to change the image elements source depending on which the contents of the source when called, this will be for mouse over and mouse out. Here's the JavaScript:

function changeImage(id) {
var src = document.getElementById(id).src;  
    if (src.search("green") != 0) {
        src = src.replace("green", "blue");
    } else {
        src = src.replace("blue", "green");
    }
    document.getElementById(id).src = src;
}   

and the HTML tag i'm using:

<img id="safety-pin" src="../images/safety-pin-green.jpg" alt="Safety pin"
    onmouseover="changeImage(id)" onmouseout="changeImage(id)"></img>

The code almost works, the images go blue, but they don't return to the green image when the mouse leaves the image, any ideas why this is?

Upvotes: 0

Views: 647

Answers (2)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11915

From MDN documentation of search,

Return value

The index of the first match between the regular expression and the given string; if not found, -1.

Replace

src.search("green") != 0

with

src.search("green") !== -1

Upvotes: 4

Zachary
Zachary

Reputation: 65

I fixed it :) a simple '>' solves my problem.

if (src.search("green") > 0) {
    src = src.replace("green", "blue");
}...

Upvotes: 0

Related Questions