Search code examples
javascripthtmlonmouseover

How do I make a div move on mouse over with javascript?


The html:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Empty</title>

<script type="text/JavaScript">

<!--

-->

</script>

</head>
<body>
<div class="blackbox" id="specialbox"><p class="boxtext">Text</p></div>
<div class="blackbox"><p class="boxtext">Hem</p></div>
<div class="blackbox"><p class="boxtext">Stugan</p></div>
<div class="blackbox"><p class="boxtext">Info</p></div>
</body>
</html>

The CSS:

body {
    background-image:url('images/bkrnd.jpg');
    background-size: cover;
    background-repeat: no-repeat;
}

.boxtext {
    color: #ffffff;
    text-align: center;
    font-family: Helvetica, Arial, sans-serif;
    font-size: 45px;
}

#specialbox {
    margin-bottom: 10px;
}

.blackbox {
    height: 75px;
    width: 400px;
    background-color: #000000;

    opacity: 0.5;
    filter:alpha(opacity=50);
    margin-bottom: 3px;
    line-height: 73px;
}

p {
margin: 0;
padding: 0;
}

When I hover the mouse over the div called "blackbox" I want it to move a little to the right. It has to be done with javascript. I've tried every bit of code and tutorials I've googled but they won't work. Thanks in advance!


Solution

  • why use javascript? its simpler with css:

    .blackbox:hover {
       margin-left: 10px;
    }
    

    working fiddle: http://jsfiddle.net/gshNP/

    for animation use:

    .blackbox:hover {
      margin-left: 10px;    
      transition: margin-left .5s;
      -moz-transition: margin-left .5s; /* Firefox 4 */
      -webkit-transition: margin-left .5s; /* Safari and Chrome */
      -o-transition: margin-left .5s; /* Opera */
    }