1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

How to change hover style with Javascript?

Discussion in 'JavaScript' started by wd_2k6, Sep 28, 2008.

  1. #1
    Hi in my CSS I have something like:


    #mydiv:hover { background: blue; }
    SEMrush
    How do I access this in my Javascript so I can change this inside my function?
     
    wd_2k6, Sep 28, 2008 IP
    SEMrush
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    perhaps something like ...
    
    <div id="mydiv">foo</div>
    
    <script>
    document.getElementById("mydiv").onmouseover = function() {
        this.style.backgroundColor = "blue";
    }
    </script>
    
    Code (markup):
     
    dimitar christoff, Sep 29, 2008 IP
  3. wd_2k6

    wd_2k6 Peon

    Messages:
    1,742
    Likes Received:
    54
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for the reply,

    Is there no way to access the :hover function inside the JS?

    I have got it working by changing the class name on click.

    This leads me to 2 final questions:

    Is it possible to get element by class rather than get element by ID?

    Is is possible to change an ID name, currently I am changing class name via:
    myvar.className="newname";
     
    wd_2k6, Sep 29, 2008 IP
  4. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #4
    yes, you can get an element by class. there is a new function that will get included in future browser releases: http://developer.mozilla.org/en/DOM/document.getElementsByClassName

    in the meanwhile you can:
    getElementsByTagName("div") ... then iterate through results and check className property of the objects...

    get a framework (check my blog on selectors).

    good luck :)
     
    dimitar christoff, Sep 29, 2008 IP