Ajarn Canz
Ajarn Canz

Reputation: 107

javascript mouseover/out combined with click behavior

I am very new in programming, please give me a mercy. Below is my code:

$(function(){
document.getElementById("custom_link").addEventListener("mouseover",function(){
document.getElementById("siteContent").contentDocument.getElementById("custom_div").classList.toggle('highlightDiv');
},false)})

$(function(){
    document.getElementById("custom_link").addEventListener("click",function(){
    document.getElementById("siteContent").contentDocument.getElementById("custom_div").classList.add('highlightDiv');
    },false)})

What I want to do is:

  1. when the user hovers mouse on "custom_link", the "custom_div" is being highlighted.
  2. when the user moves mouse out off "custom_link", the highlight at "custom_div" is eliminated.
  3. when the user clicks at "custom_link", "custom_div" is being highlight again. However, when the user moves mouse out, the 'highlightDiv' is still being added to "custom_div".

According to my code, it does not work properly because the behavior when hovering is strange. It would be very nice if you can explain me with full code structure or jsfiddle example. Thank you for your advance help.

Upvotes: 3

Views: 630

Answers (3)

Umer Farooq
Umer Farooq

Reputation: 388

here is a link http://jsfiddle.net/8GV7B/2/

 $(function(){
        mouse_is_clicked = false;
         $(".custom_link").hover(function(){ 
            $("#container").addClass("highlight");
        }, function(){ 
            if(!mouse_is_clicked){ 
                $("#container").removeClass("highlight");
            }else{
                mouse_is_clicked = false;
            }
        });

          $(".custom_link").click(function(){
               $("#container").addClass("highlight");
              mouse_is_clicked = true;
          });
    });

Upvotes: 0

Zevi Sternlicht
Zevi Sternlicht

Reputation: 5399

You are mixing Javascript with its framework jQuery. Stick with jQuery for this.

// CSS: Create the highlight accessible with two classnames.

.highlight, .highlight_stay{
    background:yellow;
}

Jquery

$(function(){
     $('.custom_link').hover(function(){
          $(this).addClass('highlight');
      }, function(){
          $(this).removeClass('highlight');
      });

      $('.custom_link').click(function(){
           $(this).addClass('highlight_stay');
      });
});

Upvotes: 1

Vinay
Vinay

Reputation: 6322

http://jsfiddle.net/ETrjA/2/

$('#custom_link').hover(function () {
    $('#custom_div').toggleClass('highlighted'); 
});

$('#custom_link').click(function (e) {
   $('#custom_div').addClass('highlighted');
   $(e.currentTarget).unbind('mouseenter mouseleave');
});

You only need one class highlighted and you can access the link element directly within the click event callback via e.currentTarget.

Upvotes: 1

Related Questions