Anmol Ratan Mohla
Anmol Ratan Mohla

Reputation: 186

How i toggle a div with 2 different images

Guys my problem is i used 2 different images for toggling a div. Image 2.gif is down arrow and image 1.png up arrow. Actually this script is the one I used for my responsive dropdown menu. So please anybody help me, where i am doing wrong.

JavaScript

<script type="text/javascript" src="jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $(".open").click(function(){
        if ($(this).img()=="<img src="2.gif" alt="" />")
            $(this).img("<img src="1.gif" alt="" />")
            else
                $(this).img("<img src="2.gif" alt="" />")
                $("div").toggle(300);
     });
  });
</script>

Css

div{ border:1px solid #000; margin:10px 10px 0 0; width:300px;    padding:10px; float:left; clear:both;}
span{float:left; width:100%;}

HTML

<span><img src="2.gif" alt="" class="open" /></span>
<div style="display:none;">test box</div>

please help my how top toggle my div currently this script not working.

Upvotes: 1

Views: 51

Answers (1)

rrk
rrk

Reputation: 15846

.img() is not a valid jQuery function, unless you are using any plugins. What needs to be done is use attr() function to get/set src attribute for an image.

$(document).ready(function(){
    $(".open").click(function(){
        if ($(this).attr('src') == "http://dummyimage.com/100x60/000/fff"){
            $(this).attr('src','http://dummyimage.com/100x60/666/000');
        } else {
            $(this).attr('src','http://dummyimage.com/100x60/000/fff');
        }
        $("div").toggle(300);
    });
});
div{ border:1px solid #000; margin:10px 10px 0 0; width:300px;    padding:10px; float:left; clear:both;}
span{float:left; width:100%;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span><img src="http://dummyimage.com/100x60/666/fff" alt="" class="open" /></span>
<div style="display:none;">test box</div>

Upvotes: 1

Related Questions