Adding an Onclick Function to Go to Url in Javascript?

Adding an Onclick Function to Go to Url in Javascript?

I am using this fancy little JavaScript to highlight a field as the user hovers over it. Could you please tell me if there is a way of adding an onclick function which will act as a link and go to a URL?

<script>
         $(function() {
            $('tr').hover(function() {
                $(this).css('background-color', '#eee');
                $(this).contents('td').css({'border': '0px solid red', 'border-left': 'none', 'border-right': 'none'});
                $(this).contents('td:first').css('border-left', '0px solid red');
                $(this).contents('td:last').css('border-right', '0px solid red');
            },
            function() {
                $(this).css('background-color', '#FFFFFF');
                $(this).contents('td').css('border', 'none');
                $('a#read_message.php').click(function(){ URL(); });
            });
        });
        </script>
2

9 Answers

Try

 window.location = url;

Also use

 window.open(url);

if you want to open in a new window.

Simply use this

onclick="location.href='pageurl.html';"
1

In jquery to send a user to a different URL you can do it like this:

$("a#thing_to_click").on('click', function(){
     window.location = "";    
});

this way will work too but the above is the newer more correct way to do it these days

$("a#thing_to_click").click(function(e){
         e.preventDefault();
         window.location = "";    
});
function URL() {
    location.href = '
}

HTML

<input type="button" value="My Button" 
onclick="location.href = '" />

MVC

<input type="button" value="My Button" 
onclick="location.href='@Url.Action("MyAction", "MyController", new { id = 1 })'" />

If you would like to open link in a new tab, you can:

$("a#thing_to_click").on('click',function(){
    window.open(' '_blank');
});

In case you're dealing with <a> tag, and you want to interrupt going to the default href you should use this instead.

Go to default url (yahoo):

<a href="" onclick="location.href='"> 

Go to new url (google) onclick:

<a href="" onclick="this.href='">

By using this you're interrupting the current browser onclick event and changing href before continuing to default behaviour of <a href='...

3

Not completely sure I understand the question, but do you mean something like this?

$('#something').click(function() { 
    document.location = '
} );
2

try

location = url;
function url() {
    location = '
}
<input type="button" value="Inline" 
onclick="location='" />

<input type="button" value="URL()" 
onclick="url()" />
Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.