www.webdeveloper.com
Results 1 to 2 of 2

Thread: A challenge for the beginner - add target blank for external links by JS.

Hybrid View

  1. #1
    Join Date
    May 2011
    Posts
    58

    Smile A challenge for the beginner - add target blank for external links by JS.

    I'm not good in JS, but I need to implement simple solution for my website. Website contains a lot of articles with this different links type:

    1. Internal links
    2. External links
    3. External links with target="_blank"
    4. External links without target="_blank"
    5. Some other JS scripts that manipulate a="#" links.

    My task is add JS script that will be open all external links in a new tab. I already try some code, that check if current link is not equal current website than open it on a new tab. But it's broke links N5, because this code t"think" that # is not equal current website url.

    Somewhere I saw great and simple solution for that, in few lines of code, but lost this link and can't find again. Please help me…

  2. #2
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,268
    A simple script (not tested)

    Code:
    var links=document.getElementsByTagName('a');
    
    for (var l=links.length,i=0;i<l;i++){
        if (/^(href|ftp)/.test(links|i])) {// external links
            if (links[i].target=='_blank') {// with target=='_blank' 
            //...  
            }
            else {// without target=='_blank'
            //...
            }
        }
        else if (/^#/.test(links|i])) {// some JS link
        //...
        }
        else {// internal links
        //...
        }    
    }

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles