Ankur
Ankur

Reputation: 51100

Add border on mouseover

I want to have a table border (which I can set using css, rather than the inline border= attribute) to be set to border: 1px solid black; when I mouseover the table.

How do I go about doing this in jQuery. I think it's identical to what's happening to the buttons at the top of this page (Questions, Tags, Users etc) except that is a div having it's background color changing whereas I want to change the border of a table. But the concept is the same.

Upvotes: 3

Views: 27746

Answers (4)

Tim M. Hoefer
Tim M. Hoefer

Reputation: 151

Alternatively, "outline" as opposed to "border" will not take up extra space in the element layout.

Upvotes: 0

Matthew James Taylor
Matthew James Taylor

Reputation: 4856

It may be better to swap classes on the table instead of editing the CSS properties directly - that would be a more scalable/extendable solution:

table {
   border:0;
}

table.border {
   border:1px solid #000;
}

Of course your table will 'jump' in position 1px when the border is added so maybe it's better to use margin or a white border when you are not hovering:

table {
   border:1px solid #fff;
}

table.border {
   border:1px solid #000;
}

Or best yet, if you don't need to be compliant with IE6 you can do it all with pure CSS:

table {
   border:1px solid #fff;
}

table:hover {
   border:1px solid #000;
}

This would be the best/simplest/scalable approach!

Upvotes: 2

Philippe Leybaert
Philippe Leybaert

Reputation: 171774

For hovering effects, jQuery provides the hover() pseudo-event, which behaves better than moueseenter/mouseleave. Also, it's a good idea to create a CSS class for each state (normal and hovered), and then change the class on hover:

$(document).ready(function() {
    $("#tableid").hover(
        function() { $(this).addClass("Hover"); },
        function() { $(this).removeClass("Hover"); }
    );
});

Your CSS could look like this:

table.Hover { border: 1px solid #000; }

Upvotes: 11

Michael La Voie
Michael La Voie

Reputation: 27926

Check out this article on the mouseenter and mouseleave events.

$("table#mytable").mouseenter(function(){
      $("table#mytable",this).css("border", "solid 1px black");
    }).mouseleave(function(){
      $("table#mytable",this).css("border", "o");
    });

Upvotes: 0

Related Questions