Reputation: 2047
So, I'm new to Javascript. In my code I have an image object that is declared like so:
<img src="me.png" id="changepic" alt="That's me!">
In my scripting code, I want to write a boolean statement that returns true when the src is "me.png" as it is in the picture and returns false if it is NOT "me.png". This boolean statement is located within the conditions of the if statement below:
function changeImage() {
if (document.getElementById("changepic").src === "me.png"){
document.getElementById("changepic").setAttribute("src", "me2.png");
}
}
I assigned the function changeImage to a button. The code for the button is written below:
<button type="button" onclick="changeImage()">Change Image</button>
For some reason, the boolean statement inside of the if statement always returns false, although the src value of the Element really is "me.png." I figured that this is a problem with how I'm writing the equality statement, but I don't know how to write an equality statement in javascript that would return true if the src value is "me.png" and return false if the src value is "me2.png". Any takers?
Upvotes: 0
Views: 360
Reputation: 70528
"Relative URIs are resolved to full URIs using a base URI. [RFC1808], section 3, defines the normative algorithm for this process. For more information about base URIs, please consult the section on base URIs in the chapter on links."
From here: http://www.w3.org/TR/1999/REC-html401-19991224/types.html#type-uri
You should just look at the "right-most" characters when you compare.
For example
var mystr = document.getElementById("changepic").src
mystr.substr(len(mystr)-6,6) === "me.png"
Upvotes: 1
Reputation: 4080
Change:
if (document.getElementById("changepic").src === "me.png"){
To:
if (document.getElementById("changepic").src.match(/me\.png$/)){
as .src will typically contain a full path to the image even though you don't specify it in the HTML.
Upvotes: 4
Reputation: 120318
The problem is not with your equality, its with
document.getElementById("changepic").src
which, is probably not returning what you think it is returning. Try a
console.log(document.getElementById("changepic").src)
and verify that it really is "me.png". I bet its something else.
Be aware that in js, ===
tests equality of both type and value, where as == will test equality more loosely; it is more forgiving. for example
2 === "2" // false because not the same type
2 == "2" // true because == tries to make the types lines up, then tests
Upvotes: 3