How to prevent redirect after hyperlink click? - javascript

I have following html+ js code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
foo
</body>
<script type="text/javascript">
function func(k){
alert(1);
return false;
}
</script>
</html>
Can you explain how to refactor following code that after click on href code func executes but # doesn't add to the URL and page shouldn't be reload?

Use javascript:void(0); instead of # as follows:
foo
Using the void operator in the href attribute of the anchor tag ensures that the browser will still display it the same way as any other anchor tag (depending on your CSS settings, this is generally a blue underlined text that changes the cursor when hovered over... etc), prevents the page redirecting to a URL that's just effectively the same page but with the added hash character (#) at the end of the address line, while also makes your onclick event to fire.

You can simply remove the href attribute:
<a id='key' onclick="func(0)">foo</a>

Change it to:
vvvvvvv
foo

To be more semantically correct I would be using a button with the following onclick:
<button id=key onclick="return func(0)">foo</button>
This way there is no need to hack around with e.preventDefault / return false.

I think you forgot the quotation marks in "key"
foo

Inside func, you could do:
func(event){ event.preventDefault(); /* More code here! */ }
preventDefault will prevent redirection, after that line, you could add any logic you want.
However, if you don't want a redirect, it is recommended to use a button instead of an a

If we want to stop redirect. We have have to return false.So we can do like that:
html:
<a onclick="return check()" href="{% url 'app_name:delete_url' item.id %}" title='Delete Item' class="btn btn-sm btn-outline-success mr-1"
<i class="fa fa-trash"></i></a>
script:
function check(){
if (confirm("Do you want to delete?") == true) {
return true;
} else {
//cancle
return false
}
}

Related

How to hide url on mouse hover of a hyper link

I'm my backend part of the app which is built in PHP Symfony I have HTML twig files, I want to change behavior for some href link, I want to hide URL in the bottom left corner after I hover them, I tried this solution that needs to change URL text to Contact, but it won't work
<a
class="activo"
href="link"
onmouseover="window.status='Contact'"
onmouseout="window.status=''"
>
Click
</a>
any help?
TL;DR; Simply use JavaScript, like:
window.location.href = "https://stackoverflow.com";
Remove the "<a ...>" element's href-attribute.
Then make it trigger a JavaScript function:
<a onclick="myFunction()">my link</a>
Finally, simply use JavaScript to redirect, like:
<script type="text/javascript">
function myFunction() {
window.location.href = "https://stackoverflow.com";
}
</script>
Note that you may need to add CSS to set cursor, I mean, already existing CSS may check href's existence, and not apply once href is removed.
Reusing same function
<a data-url="https://stackoverflow.com"
onclick="myFunction(this)">my link label</a>
<!-- In case you are using Twig or Blade: -->
<a data-url="{{ 'https://example.com' }}"
onclick="myFunction(this)">my other link</a>
<script type="text/javascript">
function myFunction(element) {
window.location.href = element.getAttribute('data-url');
}
</script>

Create an HTML button that works as a link with an "onclick"?

I'm new in HTML and I would like some help, I would like to create an HTML button that acts like a link.
So, when you click the button, it redirects to a page locally stored in the same file, which is named "page 2 html",
I have a code line:
<button type="submit">connect</button>
I would like to add a "window.onclick" function to this button which redirect to "page 2 html" and what will be the javascript function that goes with it?
Thanks.
There are a number of ways to do this, If you are stuck to a submit button, you would have to tie it to a form, then make the form's action attribute the link:
<form>
<button type="submit" formaction="https://placekitten.com/">Click Me</button>
</form>
or you could do it as a regular button:
var gimmeCats = () => {
window.location.href = "https://placekitten.com/";
}
<button id="catBtn" onclick="gimmeCats()">Click Me!</button>
Or, if you aren't opposed to bootstrap, there is this:
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
Click Me!!!!!!!!!
Using window.onclick will not do it because you are telling your browser that when you click anywhere in the window it will execute it. So you can use location.replace('') like this:
<input type="submit" onclick="location.replace('page2.html')"/>
Or using a regular button:
<button onclick="location.replace('page2.html')">Page 2</button>
Or by using a function:
<script>
function redirect() {
location.replace('page2.html');
}
</script>
<button onclick="redirect()">Redirect</button>
You could also just use a normal <a> tag:
<button>Redirect</button>

Redirecting to site from an existing button being clicked

I'm quite new to coding. I have a button with the ID='test'. I want to run a line of code in javascript or HTML to redirect users to a site when that button is clicked.
Button:
<button id="test" type="submit" onclick="setNick(document.getElementById('nick').value); return false; return false" class="btn btn-play-guest btn-success btn-needs-server primaryButton" data-itr="play_as_guest">
I tried running this:
<script>
document.getElementById("test").onclick = window.location='http://www.google.com/'
</script>
However, this would redirect straight away. I want it to redirect only when the button is clicked. Please help me fix this.
Many thanks.
You are assigning the redirect to the button where you need to assign it to a function.
You can try something like this:
document.getElementById("test").onclick = function(){
window.location='http://www.google.com/';
}
I would suggest use onclick on button, for example
your button will look like this
<button id="test" onclick="redirect()">Redirect</button>
Now in the script write the redirect function as
<script>
function redirect() {
window.location.href = "http://www.google.com/";
}
</script>

window.history.back() not working.

I cant get this to work. I have been trying for ages. Please help me.
<script>
function goBack() {
window.history.back()
}
</script>
<button onclick="goBack()">Go Back</button>
Please have a look at this question: Inconsistency with window.history.back().
this
<button type="button" onclick="goBack()">Go Back</button>
could be what you're looking for
As Kevin B suggests
The browser could be interpreting the button as a submit button and
submitting the form, thus causing a page refresh. Adding type="button"
will prevent that.
First of all, you should make sure that your script tag have the proper type set:
<script type="text/javascript">
...
</script>
Also, I would suggest using the "go" function of the history object instead since the compatibility is higher. To simplify things you can simply do this:
<button onclick="javascript:history.go(-1)">Go Back</button>
Hope this helps.
This can stop it appearing to work
<a href="#" onclick=DoSomething()>Stop it working</a>
That's because the href will effectively add a new page in the history, the present page again
Incidently if you call
event.preventDefault()
in DoSomething then # will never get added to the history and it will appear to work again
This worked for me
<button type="reset" onclick="goBack()">Go Back</button>
The window.history.back() method does not work if it does not have any previous URL to go to. Your program needs to have a start URL and you will need to have your program moving forward to the next page to be able to go back and forward.
Try preventing the default action of the button. Note that nothing will happen if you have accessed no other pages in the current tab.
Javascript:
<button id="goBack">Go Back</button>
<span id="result"></span>
<script>
document.getElementById("goBack").addEventListener("click", function(event){
event.preventDefault();
document.getElementById("result").innerHTML = "Going back";
window.history.back();
});
</script>
jQuery:
<button id="goBack">Go Back</button>
<span id="result"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('#goBack').click(function(event){
event.preventDefault();
document.getElementById("result").innerHTML = "Going back";
window.history.back();
});
</script>
Go Back
The 'return false;' bit helped fix it for me
Actually for working of this you need to redirect to this website from any other website or if you are doing on local html file then you can just open any website and paste the link of your local file in search bar in that tab(don't open a new tab) and then it will work. Basically this fuction just press the back button of your browser so you need to have something so that it can go back.

Simple JavaScript problem: onClick confirm not preventing default action

I'm making a simple remove link with an onClick event that brings up a confirm dialog. I want to confirm that the user wants to delete an entry. However, it seems that when Cancel is clicked in the dialog, the default action (i.e. the href link) is still taking place, so the entry still gets deleted. Not sure what I'm doing wrong here... Any input would be much appreciated.
EDIT: Actually, the way the code is now, the page doesn't even make the function call... so, no dialog comes up at all. I did have the onClick code as:
onClick="confirm('Delete entry?')"
which did bring up a dialog, but was still going to the link on Cancel.
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<script type="text/javascript">
function delete() {
return confirm('Delete entry?')
}
</script>
...
<tr>
<c:if test="${userIDRO}">
<td>
<a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}"/>" />
<img src="images/edit.GIF" ALT="Edit this skill." border="1"/></a>
</td>
<td>
<a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}&remove=1"/>" onClick="return delete()"/>
<img src="images/remove.GIF" ALT="Remove this skill." border="1"/></a>
</td>
</c:if>
</tr>
There's a typo in your code (the tag a is closed too early).
You can either use:
<img ...>
note the return (confirm): the value returned by scripts in intrinsic evens decides whether the default browser action is run or not; in case you need to run a big piece of code you can of course call another function:
<script type="text/javascript">
function confirm_delete() {
return confirm('are you sure?');
}
</script>
...
<img ...>
(note that delete is a keyword)
For completeness: modern browsers also support DOM events, allowing you to register more than one handler for the same event on each object, access the details of the event, stop the propagation and much more; see DOM Events.
Well, I used to have the same problem and the problem got solved by adding the word "return" before confirm:
onclick="return confirm('Delete entry?')"
I wish this could be heplful for you..
Good Luck!
I use this, works like a charm. No need to have any functions, just inline with your link(s)
onclick="javascript:return confirm('Are you sure you want to delete this comment?')"
I had issue alike (click on button, but after cancel clicked it still removes my object), so made this in such way, hope it helps someone in the future:
$('.deleteObject').click(function () {
var url = this.href;
var confirmText = "Are you sure you want to delete this object?";
if(confirm(confirmText)) {
$.ajax({
type:"POST",
url:url,
success:function () {
// Here goes something...
},
});
}
return false;
});
Using a simple link for an action such as removing a record looks dangerous to me : what if a crawler is trying to index your pages ?
It will ignore any javascript and follow every link, probably not a good thing.
You'd better use a form with method="POST".
And then you will have an event "OnSubmit" to do exactly what you want...
First of all, delete is a reserved word in javascript, I'm surprised this even executes for you (When I test it in Firefox, I get a syntax error)
Secondly, your HTML looks weird - is there a reason you're closing the opening anchor tags with /> instead of just > ?
<img src="images/delete.png" onclick="return confirm_delete('Are you sure?')">
<script type="text/javascript">
function confirm_delete(question) {
if(confirm(question)){
alert("Action to delete");
}else{
return false;
}
}
</script>
If you want to use small inline commands in the onclick tag you could go with something like this.
<button id="" class="delete" onclick="javascript:if(confirm('Are you sure you want to delete this entry?')){jQuery(this).parent().remove(); return false;}" type="button">
Delete
</button>
try this:
OnClientClick='return (confirm("Are you sure you want to delete this comment?"));'
I've had issue with IE7 and returning false before.
Check my answer here to another problem: Javascript not running on IE

Categories