SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Feb 2006
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Dynamically prepend onclick events in page.

    I have a page that uses an onclick event to do a link with location.href. I do not have access to the code that creates these links. I want a function that will dynamically prepend "top." to the beginning of the onclick event, making it onclick="top.location.href=''", rather than onclick="location.href=''".

    Any suggestions?

  2. #2
    SitePoint Member
    Join Date
    May 2007
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I got it tcovert.

    Get the onclick function into a string. Extract the URL from the function using regular expressions. Then set the onclick function of the link. You can't just append the onclick attribute of each link. The onclick attribute is actually a function, and you can't append dynamically to a function. Therefore, you have to read the function as a string, extract the URL, and then create a whole different function. Like this:

    Code:
    <script type="text/javascript">
    var links = new Array();
    links = document.getElementsByTagName('a');
    for(var i=0;i<links.length;i++){
    	var tempfunc = links[i].onclick;
    	//*****EXTRACT THE URL*****//
    	var url = "http://www.sitepoint.com"; //say this is the url you extracted
    	links[i].onclick=function(){top.location.href=url};
    }
    </script>
    Need help extracting the URL? Make another post lol: How do I extract a URL from a string in Javascript?

    PEACE!

  3. #3
    SitePoint Member
    Join Date
    Feb 2006
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I will need help with the url extraction part, and I posted a ticket for that. However, I started ding some testing with the code you gave, usng just the default url variable, and I can't get it to work. Now, you had it setup to look for an "a" tag, but in this case the onclick is actually on a "td" tag. So, I changed that out and tried it, but still no luck. Here is an example:

    <td class="s29999" style="cursor: pointer;" onclick="location.href='http://calendar.kitsapsun.com/ellington_index.php?ev=2454222&mo=5&yr=2007'">1</td>

    Any ideas?

  4. #4
    SitePoint Member
    Join Date
    Feb 2006
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Nevermind my last post, it works awesome. I just need the url part.


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
  •