droidus
droidus

Reputation: 641

How to add border to image on hover?

I am trying to add a border to an image on rollover. The border is not showing when I roll over the image. Here is my code:

<script>
$(document).ready(function() {
    $("#imgBorder").hover(
        function() { $(this).addClass("Hover"); },
        function() { $(this).removeClass("Hover"); }
    );
});
</script>
Hover { border: 1px solid #000; }
<div id="imgBorder"><a href="#">link...</a>

Why isn't the border appearing on hover?

Also, is there any way to do this so that it does not re-size the image when adding the border?

Upvotes: 0

Views: 2484

Answers (4)

David Thomas
David Thomas

Reputation: 253486

First, to affect the image, your jQuery should be:

$("#imgBorder img").hover(
    function() { $(this).addClass("Hover"); },
    function() { $(this).removeClass("Hover"); }
);

And your CSS should be:

.Hover { /* note the period preceding the 'Hover' class-name */
    border: 1px solid #000;
}

JS Fiddle demo.

Note that:

  • .string selects element(s) by their class-name of string: <div class="string"></div>
  • #string selects an element by its id, which is equal to string <div id="string"></div>
  • string selects an element of string: <string></string>

But you don't need JavaScript, just use:

#imgBorder:hover img,
#imgBorder img:hover {
    border: 1px solid #000;
}

JS Fiddle demo.

Upvotes: 1

Sampson
Sampson

Reputation: 268462

In your selector below, you're targeting an element with the tagname "Hover". This does not exist.

Hover { border: 1px solid #000; }

What you wanted instead was:

.Hover { border: 1px solid #000 }

As others here have already pointed out, you don't need JavaScript for this as you can use the :hover pseudo-class:

img { border: 1px solid #FFF }
img:hover { border-color: #000; }

For further reading, see http://www.w3.org/TR/CSS2/selector.html#dynamic-pseudo-classes

Upvotes: 0

Jonathan Payne
Jonathan Payne

Reputation: 2223

You do not need to use javascript to add hover on image rollover. Just add it to the css class instead.

<style language="text/css">
.rollOver : hover
{
    border: 1px solid #000;
}
</style>

<div class="rollOver" id="imgBorder">Test</div>

Upvotes: 2

Brad Fox
Brad Fox

Reputation: 681

Something like this will work in CSS, link below

.rollover_img {
width: 280px;
height: 150px;
background-image: url(land.jpg); 
background-position: top;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border:10px solid #ccc;
font:13px normal Arial, Helvetica, sans-serif;
line-height:18px;
float:left;
margin:0 10px 10px 0;
}

I will direct you to the following link

http://aceinfowayindia.com/blog/2010/02/how-to-create-simple-css-image-rollover-effect/

Upvotes: 0

Related Questions