kunz
kunz

Reputation: 1047

toggling with image jquery

when clicked on add_hide_calculator I would like the image to change in to calculator_open-img, and when clicked again, I would like the image to change back. This is what I have so far I am unable to change the picture on click:

Jquery.js

$('#add_hide_calculator').on("click", function() {
    var text = $(this).val();
    $("#calculator").toggle();
});

$(window).on("click keydown", function(e) {
  //e.preventDefault()
  //sets the esc key button 
  if (e.keyCode === 27 || !$(e.target).is(function() {return $("#calculator, #add_hide_calculator")})) {
    $("#calculator").hide()
  }
}).focus()

/* toggling image starts here */

$('#add_hide_calculator').on("click", function() {
    var text = $(this).text();

    if (text == "<img src='calculator_open-img.png' width='200px' height='190px'>") {
      $(this).html("<img src='calculator_close-img.png' width='200px' height='190px'>");
    } else {
      $(this).html("<img src='calculator_open-img.png' width='200px' height='190px'>");
    }
});

Index.php

<a id="add_hide_calculator"><img src="calculator_close-img.png" width="200px" height="190px"></a>

Upvotes: 1

Views: 30

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388326

You can check for the src attribute value

$('#add_hide_calculator').on("click", function() {

  $(this).find('img').attr('src', function(i, src) {
    return src == "calculator_open-img.png" ? "calculator_close-img.png" : "calculator_open-img.png";
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<a id="add_hide_calculator">
  <img src="calculator_close-img.png" width="200px" height="190px">
</a>

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

change this line

var text = $(this).text();

to

var text = $(this).html();

you basically are comparing the html inside the anchor (link) not the text. Text is what you finally see after html is rendered.

Upvotes: 1

Related Questions