Search code examples
javascriptjqueryfunctionpreventdefault

preventDefault() like functionality in javascript


I have already gone through this question

event.preventDefault() vs. return false

But didn't find my solution. Actually i am using javascript function to go back to previous page that is working fine on click of

<a href="#" onclick="goBack()"><img src="images/backbtn.png"></a>

function

function goBack(){
    window.history.back();
}

When i click on <a> it includes # in url which i want to prevent. In jquery we use preventDefault() to stop the default event of an element but is there any similar function in javascript to stop it.

I know i can use javascript:void(0) in href which will solve the problem but there can be many other instances so i want to know about function in javascript.

I tried using return false; but it i write this on top like this

function goBack(){
    return false;
    window.history.back();
}

Then it stops the function to execute and if i write like this

function goBack(){
    window.history.back();
    return false;
}

Then no effect from this return false;. I am sure there is some in javascript as jquery is generated from javascript.

Any help would be appreciated. Thanks in advance!


Solution

  • As far as I know, preventDefault() also is a native JS function, so you can use it without jQuery and get same result.

    You can read more about it here: MDN: Event.preventDefault()