Tibneo
Tibneo

Reputation: 39

jQuery Show/Hide on Hover // Show on Click

I have a question related to this one:

jQuery hover (show-hide)

However, in his fiddle,

http://jsfiddle.net/Q5cRU/27/

He has two divs

<div id="rectangle"></div>
<div class="rectangle1"></div>

They are similar, but different colored

      rectangle {
      width: 140px; 
      height: 80px;
      background: #037CA9;
      margin-bottom:10px;
}

      .rectangle1 {
      width: 140px; 
      height: 150px;
      background: #37CA90;
}

How would he be able to click the dark blue rectangle to make the light blue rectangle stay?

If you load the fiddle, all the code is there.

Upvotes: 2

Views: 1882

Answers (4)

Ploxer
Ploxer

Reputation: 88

You just have to remove the class and add a similar one containing the same css properties, that way hover wont trigger after it has been clicked. here is an updated fiddle.

$('#rectangle').click(function(){
    $('.rectangle1').addClass('rectangle2');
    $('.rectangle1').removeClass('rectangle1');
});

CSS

.rectangle1, .rectangle2  {
   width: 140px; 
   height: 150px;
   background: #37CA90;
}

EDIT: Code optimized, fiddleJS link updated.

Upvotes: 0

StuartLC
StuartLC

Reputation: 107247

Keep a state flag which toggles if the rectangle is clicked:

$(document).ready(function(){
  var clicked=false;

  $('.rectangle1').hide();

    $('#rectangle').on('click', function() {
        clicked = !clicked;
    });

    $('#rectangle').hover(
      function() {
        $('.rectangle1').show()}
      ,function() {
          if (!clicked) {
             $('.rectangle1').hide()
          }
      }
    );  
});

jsFiddle: http://jsfiddle.net/Q5cRU/34/

Similarly, clicking it again allows the bottom rectangle to hide.

Upvotes: 2

Hussnain Cheema
Hussnain Cheema

Reputation: 161

$(document).ready(function(){
    $('.rectangle1').hide();

  $('#rectangle').hover(function() {
 $('.rectangle1').show()
  },function() {
      $('.rectangle1').hide()
  });  
});

In this code, it is clear that on hovering rectangle with id is equal to rectangle, rectangle1 is shown to us. It is simple jquery code.

Upvotes: 0

Amir Parsa KHademi
Amir Parsa KHademi

Reputation: 105

replace the javascript code :

$(document).ready(function(){
    $('.rectangle1').hide();

  $('#rectangle').click(function() {
 $('.rectangle1').show()
  });
});

Upvotes: 0

Related Questions