TechnoBlahble
TechnoBlahble

Reputation: 633

Image toggle button works only once

I have an image button, which I am trying to toggle. However, it toggles only once on refresh. When i click on the image, it should change to the second picture, and on the next click, change back to the oroginal picture. Through this code, I can get to the second picture from the first, but I can't get the original picture back when I click again. Can someone point out where I am going wrong? This is the whole script that I am using

HTML & jQuery -

<a href='#'>
        <input type="image" src="/images/pulpit.jpg" id="btn-true" />
</a>


<script type="text/javascript">
            $('#btn-true').click( function () {
                if ($(this).prop("src", "/images/pulpit.jpg"))
                    $(this).prop("src", "smiley.gif");
                else if ($(this).prop("src", "smiley.gif"))
                    $(this).prop("src", "/images/pulpit.jpg");
            });
        </script>

Upvotes: 0

Views: 383

Answers (3)

glautrou
glautrou

Reputation: 3198

Instead of checking and changing the image URL you should deal with CSS classes. For example when you click on the image, you check if this image is toggled or not.

if ($(this).hasClass("toggle"))
    $(this).removeClass("toggle");
else
    $(this).addClass("toggle");

Then you specify your image path in your CSS.

img { background-image:url(/images/pulpit.jpg); }
img.toggle { background-image:url(smiley.gif); }

EDIT:

Replace the content of you JavaScript function by

$(this).toggleClass('toggle');

The result will be exactly the same but as mentionned by @Eric it is much better to use the toggleClass() method.

Each time you click on the image the "toggle" CSS class will be added if it is not already, otherwise it will be deleted.

Then you can manage this in CSS (in your case add the two css classes mentioned above for displaying a different image).

Upvotes: 0

Eric
Eric

Reputation: 18922

First of all you shall use .attr() for attributes, and .prop() for properties. Then you need to compare the output, not set it as you currently trying to. Take a look at this:

$('#btn-true').click( function () {
                if ($(this).attr("src") == "/images/pulpit.jpg") {
                    $(this).attr("src", "smiley.gif");
                } else if ($(this).attr("src") == "smiley.gif") {
                    $(this).attr("src", "/images/pulpit.jpg");
                }
            });

Upvotes: 0

tymeJV
tymeJV

Reputation: 104785

Your conditional statements are a little wrong, you're actually assigning a source in your check, change the lines:

if ($(this).prop("src", "/images/pulpit.jpg"))
else if ($(this).prop("src", "smiley.gif"))

To:

if ($(this).prop("src") == "/images/pulpit.jpg")
else if ($(this).prop("src") == "smiley.gif")

Upvotes: 2

Related Questions