Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery click event on div

I have this code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
.kat1 {
    background-image:url(ikoniceKategorije/07.jpg);
    width:30px;
    height:30px;
    float:left;
    }
.kat1:hover {
    background-image:url(ikoniceKategorije/07h.jpg);
    }

// here I have a code for .kat2,kat2 ... styles
#div {
    width:220px;
    height:30px;
    overflow:hidden;
    }

</style>
<script>
$(function() {
  $('#div div').click(function() {
    var elem = $(this);
    var style = elem.css('background-image');
    if(/h\.jpg/.test(style)) {
      elem.css('background-image', style.replace(/h\.jpg/, '.jpg'));
    } else {
      elem.css('background-image', style.replace(/\.jpg/, 'h.jpg'));
    }
  });
});
</script>
</head>

<body>

    <div id="div">
        <div class="kat1 changing"></div> 
        <div class="kat2 changing"></div>
        <div class="kat3 changing"></div>
        <div class="kat4 changing"></div>
        <div class="kat5 changing"></div>
        <div class="kat6 changing"></div>
        <div class="kat7 changing"></div>
    </div>
</body>
</html>

I have a problem - when I click once div change bacground color but when I click second time on same icon then I cant change div background...

demo www.pluspon.com/kategorije.html

like image 735
Miki Cloud Avatar asked May 18 '26 21:05

Miki Cloud


1 Answers

Why do you want to have this functionality in JavaScript? An other option would be to use CSS classes to simplify the process:

$(function() {
  $('#div div').click(function() {
    $(this).toggleClass('active');
  });
});

CSS:

.kat1 {
    background-image:url(ikoniceKategorije/07.jpg);
    width:30px;
    height:30px;
    float:left;
}
.kat1:hover,
.kat1.active {
    background-image:url(ikoniceKategorije/07h.jpg);
}
like image 145
Richard Avatar answered May 21 '26 09:05

Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!