0

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?

0

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

I see, I wasn't to sure how the search feature works. thank you :)
0

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

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

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.