Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vanilla javascript classList manipulation on hover

Trying to do some really basic class manipulation on hover and load for a splash page. Not sure why it's not working- then again, never written in Vanilla before.

jsFiddle example.

basic DOM:

<body>
    <article>
        <p>test</p>
    </article>
</body>

JavaScript:

var bod     = document.getElementsByTagName('body')[0],
    article = document.getElementsByTagName('article')[0];

article.onMouseOver = function(){

    bod.classList.add('focus');
}

article.onMouseOut = function(){

    bod.classList.remove('focus');
}

window.onLoad = function(){

    bod.classList.remove('loading');
}
like image 593
technopeasant Avatar asked Jan 14 '23 07:01

technopeasant


1 Answers

use lowercase handlers:

article.onmouseover

But in general it's better to use the addEventListener method. The .onevent method allows for only one handler and its also quick and dirty. however it messes up the code and the html and in some cases you might even remove some other important code from running, that is why the addEventListener is better, as it chains and you can have multiple handlers listening to one event, which is the proper form.

Here is a wonderful answer from another stackoverflow user on the exact differences (however I pretty much sum it up for you in the above paragraph).. AddEventListener vs element.onevent

here is the fixed Fiddle using the proper event handling: http://jsfiddle.net/hXjFz/1/

like image 138
Dory Zidon Avatar answered Jan 18 '23 12:01

Dory Zidon