Hello guys!

I'm trying to change an element background color when my mouse goes over another element. As far as I know CSS, this seems to be impossible to do only with CSS, so what kind of js I need to do this? My knowledge in JavaScript it too limited for me to figure on my own.

Thanks!

Recommended Answers

All 16 Replies

toggleXprop=
    function(o,p,v){
            o.m||(o.m={});
            o[p]==v?o[p]=o.m[p]:(o.m[p]=o[p],o[p]=v);
    }

usage:

handlerElement.setAttribute("onmouseover", 
     "toggleXprop(targetElement.style, 'backgroundColor', 'colorVal')");

handlerElement.setAttribute("onmouseout",
     "toggleXprop(targetElement.style, 'backgroundColor', '')");

I will show you a simple way to do using style, CSS, and (inline) Javascript. Below is a script changing color of 2 boxes using javascript but in a different way -- one is accessing 'style' property of the element and the other is to change its CSS class.

<html>
<head>
<style type="text/css">
div.box {
  width: 100px;
  height: 100px;
  border: 2px solid black;
}
div.bgGreen {
  background-color: green;
}
div.bgBlue {
  background-color: blue;
}
</head>
</style>
<body>
  <div style="width:100px;height:100px;border:2px solid black;background-color:red" onmouseover="this.style.backgroundColor='yellow'" onmouseout="this.style.backgroundColor='red'">
  Box1
  </div>
  <div class="box bgGreen" onmouseover="this.className=this.className.replace('bgGreen', 'bgBlue')" onmouseout="this.className=this.className.replace('bgBlue', 'bgGreen')">
  Box2
  </div>
</body>
</html>

"trying to change an element background color when my mouse goes over another element."

Hmm... Not sure what that mean... :( Too vauge... Anyway, the example I made is just to show a very simple wayt to change background color using mouse event of each element. May not be a solution. :)

This is not impossible to do with CSS if the elements are next to each other. It's not recommended to rely on that though in case elements get moved around but here is how it's done just as an FYI:

HTML:

<div class="one"></div>
<div class="two"></div>

CSS:

.one,
.two {
    width: 80px;
    height: 80px;
}

.one {
    background-color: red;
}

.two {
    background-color: blue;
}

.one:hover + .two {
    background-color: green;
}

Quoted Text Here

Hmm... Not sure what that mean... :( Too vauge... Anyway, the example I made is just to show a very simple wayt to change background color using mouse event of each element. May not be a solution. :)

The sentence: "trying to change an element background color when my mouse goes over another element."
would usually mean: I need to change the background of element B, when element A is hovered :p

My Spartan (universal property toggle) happens to be the right tool for the job since it is not bound to the event source element, therefore its action can arbitrarilly target any element on the document, on an iframe, on a popup window; including itself. ;)

This is not impossible to do with CSS if the elements are next to each other. It's not recommended to rely on that though in case elements get moved around but here is how it's done just as an FYI:

True,
but you should warn about browser compatibility;
-not all versions support pseudo-classes on ordinary elements;

Love your hair though :)

Well you're talking about IE6 which also doesn't support the adjacent sibling selector... but I was only demonstrating that it can be done in the most commonly used browsers today, not teaching the ins and outs of browser compatibility :)

Thanks, I love my hair too haha ;)

commented: Impressive! You make me proud! :D +7

I've been away for what, two days, and now I have all these answers! Thanks guys.

Troy III, can you explain your code a little more? I'm such a novice on JavaScript and don't know how to use it.

JJenZz, your code didn't worked on Chrome.

Let me explain a bit better what I want: my site has a line on its top, like a header, and right below it has a menu consisted only of links (no lists). What I want to do is that when the cursor goes on a link, the line on the top of the page gets the same background color of the hovered link, since each link will have different colors.

I can share my CSS and my HTML file if it is needed.

it helps if you post the relevant code.

Ok, so this is the code of the menu and the line I said:

<div class="linha"></div>
<div id="wrapper">
    <div id="menu"><a href="home.html" class="home active">h o m e</a><a href="#" class="trabalhos">t r a b a l h o s</a>
        <a
        href="#" class="experimentos">e x p e r i m e n t o s</a><a href="contato.html" class="contato">c o n t a t o</a>    
    </div>        

and these are the CSS styles that match the ids/classes above:

.linha {
          width: 100%;
          height: 3px;
          background-color: #E51400;
}
#menu {
        width: 100%;
        text-align: center;
        font-weight: 400;
        font-size: 1.6em;
        color: #333;
}
.home {
        text-decoration: none;
        border-bottom-width: 1px;
        border-bottom-style: dotted;
        border-bottom-color: #E51400;
        padding-right: 5px;
        padding-left: 5px;
        margin: 10px;
        -webkit-transition: all .2s ease-in-out 0s;
        -moz-transition: all .2s ease-in-out 0s;
        -ms-transition: all .2s ease-in-out 0s;
        -o-transition: all .2s ease-in-out 0s;
        transition: all .2s ease-in-out 0s;
        color: #333;
}
.home:hover {
          background-color: #E51400;
          color: #fff;
}
.home.active {
          background-color: #E51400;
          color: #fff;
}
.trabalhos {
        text-decoration: none;
        border-bottom-width: 1px;
        border-bottom-style: dotted;
        border-bottom-color: #E51400;
        padding-right: 5px;
        padding-left: 5px;
        margin: 10px;
        -webkit-transition: all .2s ease-in-out 0s;
        -moz-transition: all .2s ease-in-out 0s;
        -ms-transition: all .2s ease-in-out 0s;
        -o-transition: all .2s ease-in-out 0s;
        transition: all .2s ease-in-out 0s;
        color: #333;
}
.trabalhos:hover {
        background-color: #8CBF26;
        border-bottom-color: #8CBF26;
        color: #fff;
}
.trabalhos.active {
          background-color: #8CBF26;
        border-bottom-color: #8CBF26;
          color: #fff;
}

.experimentos {
        text-decoration: none;
        border-bottom-width: 1px;
        border-bottom-style: dotted;
        border-bottom-color: #E51400;
        padding-right: 5px;
        padding-left: 5px;
        margin: 10px;
        -webkit-transition: all .2s ease-in-out 0s;
        -moz-transition: all .2s ease-in-out 0s;
        -ms-transition: all .2s ease-in-out 0s;
        -o-transition: all .2s ease-in-out 0s;
        transition: all .2s ease-in-out 0s;
        color: #333;
}
.experimentos:hover {
        background-color: #6E155F;
        color: #fff;
        border-bottom-color: #6E155F;
}
.experimentos.active {
        background-color: #6E155F;
        color: #fff;
        border-bottom-color: #6E155F;
}

.contato {
        text-decoration: none;
        border-bottom-width: 1px;
        border-bottom-style: dotted;
        border-bottom-color: #E51400;
        padding-right: 5px;
        padding-left: 5px;
        margin: 10px;
        -webkit-transition: all .2s ease-in-out 0s;
        -moz-transition: all .2s ease-in-out 0s;
        -ms-transition: all .2s ease-in-out 0s;
        -o-transition: all .2s ease-in-out 0s;
        transition: all .2s ease-in-out 0s;
        color: #333;
}
.contato:hover {
        background-color: #1BA1E2;
        border-bottom-color: #1BA1E2;
        color: #fff;
}
.contato.active {
        background-color: #1BA1E2;
        border-bottom-color: #1BA1E2;
        color: #fff;
}

Wrapper is nothing but the page size.

I'm trying to make the line div to have the same color as the hover link inside menu.

Hope this helps.

do you use a separate towel on each hand?!
-well than, you'll need to take it easy on those CSS definitions.

This is the exact equivalent of your existing css, [except that it is at least 1/4 times shorter].

.linha {
          width: 100%;
          height: 3px;
          background-color: #E51400;
}
#menu {
        width: 100%;
        text-align: center;
        font-weight: 400;
        font-size: 1.6em;
        color: #333;
}
.home,.contato,.trabalhos,.experimentos  {
        text-decoration: none;
        border-bottom-width: 1px;
        border-bottom-style: dotted;
        border-bottom-color: #E51400;
        padding-right: 5px;
        padding-left: 5px;
        margin: 10px;
        -webkit-transition: all .2s ease-in-out 0s;
        -moz-transition: all .2s ease-in-out 0s;
        -ms-transition: all .2s ease-in-out 0s;
        -o-transition: all .2s ease-in-out 0s;
        transition: all .2s ease-in-out 0s;
        color: #333;
}

.home:hover,.home.active {
          background-color: #E51400;
          color: #fff;
}
.trabalhos:hover,.trabalhos.active {
        background-color: #8CBF26;
        border-bottom-color: #8CBF26;
        color: #fff;
}

.experimentos:hover,.experimentos.active {
        background-color: #6E155F;
        color: #fff;
        border-bottom-color: #6E155F;
}
.contato:hover,.contato.active {
        background-color: #1BA1E2;
        border-bottom-color: #1BA1E2;
        color: #fff;
}

but even this can stand a trial for further optimizations.

***

The following JavaScript function can do your thing, - if you agree to remove css transitions...

   activate : syncAttr(lineTop.style, "backgroundColor", menu.children);    
     function syncAttr(t, a, x){
            function cS(x){return getComputedStyle(x,0) || x.currentStyle};
            var L = x[0] ? x : [x], i = 0;
            while(L[i]){ 
                L[i].onmouseover= attSync;
                L[i].onmouseout = function(){t[a]=""};
            i++;}
            function attSync(){t[a] = cS(this)[a]}
            }

The code is assuming that: <div class="linha"></div> has an id=lineTop. That is <div id=lineTop class=linha></div>.

But as mentioned; Will not work with css transitions enabled.

nice job!

Troy III, thanks for the help, but there isn't any way to do it with animations/transitions?

And, well, my CSS wasn't ready at all, since I'm still at the beginning of the site. It may change completly... I'm thinking that I might use only one color since what I want appears to not work without animations...

Troy III, thanks for the help, but there isn't any way to do it with animations/transitions?

There is, but I don't like fixed things,
-however, this will do until you find a better approach.

demo:
http://jsfiddle.net/KWUHy/6/

the snip:

   activate : syncAttr(lineTop.style, "backgroundColor", menu.children);    

     function syncAttr(t, a, x){
            function cS(x){return getComputedStyle(x,0)||x.currentStyle};
            var L = x[0] ? x : [x], i = 0, z,tm;
            while(L[i]){ 
                L[i].onmouseout = function(){t[a]="";clearInterval(tm)};
                L[i++].onmouseover= attSync;}
            function attSync(){z=this; 
                tm=setInterval(function(){
                if(/rgba|tran/.test(cS(z)[a])){ t[a]=cS(z)[a];
                }else{ t[a]=cS(z)[a]; clearInterval(tm) }},8)}
            }

Well, its been a quite time, so I thought it would be nice to give some feedback.

I'm not working on any project that needs this right now, neither I think I'll be working on it in a near future. Thanks for everyone's help, I managed to get it working anyway with the piece of code that Troy III provided right above me.

Cheers!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.