0

trying to swap two images depending on which the user has clicked.

so it should hide the image that the user has just clicked and show the one that was hidden.

must be something simple wrong here...

<!-- toggle for contrast buttons -->
<script type=text/javascript>
        $("a.contrast-button").click(function () {
            $("a.contrast-button").toggle();
        });
</script>



<div class="span-16 last" id="access-controls">
    <a class="contrast-button" id="switchDark" href="#"><img src="/static/images/contrast-dark.png" /></a>
    <a class="contrast-button" id="switchRed" style="display:none;" href="#" ><img src="/static/images/contrast-light.png" /></a>
    <a class="access-nav" href="#">contrast:</a>
</div>

1 Answer 1

1

Works as long as you assign the handler on .ready().

Example: http://jsfiddle.net/6NvN8/

 // v------ensures the DOM is ready before running code within
$(function() {
    $("a.contrast-button").click(function() {
        $("a.contrast-button").toggle();
    });
});

If the order of your code is exactly as you show it in the question, then the elements do not exist yet when the jQuery code runs.

If you just flipped it around, it would also make it work.

Example: http://jsfiddle.net/6NvN8/1

<div class="span-16 last" id="access-controls">
    <a class="contrast-button" id="switchDark" href="#"><img src="/static/images/contrast-dark.png" /></a>
    <a class="contrast-button" id="switchRed" style="display:none;" href="#" ><img src="/static/images/contrast-light.png" /></a>
    <a class="access-nav" href="#">contrast:</a>
</div>


<!-- toggle for contrast buttons -->
<script type=text/javascript>
        $("a.contrast-button").click(function () {
            $("a.contrast-button").toggle();
        });
</script>

This is because the elements have a chance to load before your script runs.

Sign up to request clarification or add additional context in comments.

3 Comments

I've had it working in a fiddle too, but nothing in the actual page. how do i trouble shoot this? i know i crack open firebug but not sure what i need to do then.
just seen your edit. i've shifted the js to the footer, before the /body tag and it still doesn't run.
@shofty: First look for errors in the console using the browser's developer tools. If no errors, then there must be some issue in code that you haven't posted.

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.