SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Which method is better?

    Hello,

    I'm creating a script like this:
    Code:
    this is <span onmouseover="callafunction()" onmouseout="callafunction()"><span onmouseover="callafunction()" onmouseout="callafunction()">inner text</span> inside another span</span> and this is outer text.
    As you can see, there are <span>'s with the same onmouseover and onmouseout event, and these will be a lot, is there any way to make the code neater?

    I'm thinking to use DHTML to add the events on runtime, so in my code it will be like this:
    Code:
    this is <span><span>inner text</span> inside another span</span> and this is outer text.
    then I'll scan and add the onmouse* events to the <span>'s, is it possible? which one is lighter for browser? I assume if it's lighter then it will be faster too, both on loading and processing time.

    Your opinion please, thanks in advance.

  2. #2
    SitePoint Evangelist
    Join Date
    Mar 2006
    Location
    Sweden
    Posts
    451
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Use the latter, since it's always a good thing to separate HTML and Javascript. Put a div around your spans, set an id on the div and the get all spans in that div, and add onmouseover and onmouseout to them. Your HTML will look alot cleaner, and you can add spans in the div which automatically will have the events attached to them.

  3. #3
    SitePoint Evangelist hexburner's Avatar
    Join Date
    Jan 2007
    Location
    Belgium
    Posts
    591
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would add them dynamically with an onload function.
    It's slower though, but almost unnoticable.
    FOR SALE: 1 set of morals, never used, will sell cheap

  4. #4
    SitePoint Enthusiast
    Join Date
    Jun 2007
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You could attach event handlers using the DOM. To access all your spans you could wrap them into a div with an id and then do like this:

    HTML Code:
    var div = document.getElementById("div_with_spans");
    
    for (var i = 0; i < div.childNodes.length; i++)
    {
       div.childNodes[i].onmouseover = callafunction;
       div.childNodes[i].onmouseout = callafunction;
    }

  5. #5
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay, seems like everyone suggested me to create it dynamically. Thanks for all your replies!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •