Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jul 2008
    Posts
    29
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Change Link With Jquery (or javascript)

    I'm trying to change one of my link's href properties with jquery, so that when the page loads, it changes the links href from one link to a different link? The goal is to use when link is the user has javascript, and another if they do not.

  • #2
    Gütkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    Say you have this link here in your HTML:

    Code:
    <a id="link" href="http://originallink">link</a>
    You can change the href with
    Code:
    $(document).ready(function(){
    	$('#link').attr('href', 'http://changedlink');
    });
    If for some reason you want to change the link, but still want the old link to show in the status bar when hovering, you can do it like this:
    Code:
    $(document).ready(function(){
    	$('#link').click(function(event){
    		window.location = 'http://hiddenlink';
    		event.preventDefault();
    	});
    });
    Notice that this is jQuery. In vanilla Javascript it's

    Code:
    window.onload = function () {
    	document.getElementById('link').href = 'changedlink';
    }
    or

    Code:
    window.onload = function () {
    	document.getElementById('link').onclick = function () {
    		window.location = 'http://hiddenlink';
    		return false;
    	}
    }
    If you already have another onload handler, in the vanilla version you will have to use addEventListener and attachEvent instead of window.onload though.


  •  

    Posting Permissions

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