Let's say I have the following link:
Click Me!
When clicked this link will alert a message as well as appending a pound sign on the end of the page url. This doesn't look very pretty is there any way to avoid it besides using javascript in the url itself:
Click Me!
You have to prevent the default response from occurring.
The old-fashioned approach is to return false from it:
Click Me!
Or, better:
Click Me!
<script type="text/javascript">
window.onload = function() {
document.getElementById('myLink').onclick = function(event) {
alert('You clicked a link.');
return false;
};
};
</script>
The best approach nowadays is to call the proper method of the event property:
Click Me!
<script type="text/javascript">
window.onload = function() {
document.getElementById('myLink').onclick = function(event) {
alert('You clicked a link.');
event.preventDefault(); // <---
};
};
</script>
It's also best to replace that # with an URI to some proper page, for people not using JavaScript. In some jurisdictions, accessibility is in fact a legal requirement.
Edit Fixed for bleedin' IE:
function f() {
document.getElementById('myLink').onclick = function(e) {
alert('You clicked a link.');
if (!e) {
var e = window.event;
}
// e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = false;
// e.stopPropagation works only in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
};
window.onload = f;
The trick is return false on the event handler.
Click Me!
Related
I want browser to perform default behaviour after doing some stuff. I used even.preventDefault() and return. But Return to click event is not performing default browser behaviour?
var doneStuff = false;
$('a').on('click', function(event) {
if(doneStuff){
alert('done');
doneStuff = false;
return;
}
event.preventDefault();
alert('doning stuff');
doneStuff = true;
$(this).trigger('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Some Link
Return is performing default browser behavior.
The problem here is $(this).trigger('click').
Unfortunately that only triggers click event handlers that were registered through jQuery (not native js dom events).
So you just should to call native click method:
var doneStuff = false;
$('a').on('click', function(event) {
if(doneStuff){
alert('done');
doneStuff = false;
return;
}
event.preventDefault();
alert('doning stuff');
doneStuff = true;
this.click();
});
Take a look at stackblitz
You can do this using set attr at run time and then after click.
var doneStuff = false;
$('a').on('click', function(event) {
if(doneStuff){
alert('done');
doneStuff = false;
return;
}
event.preventDefault();
alert('doning stuff');
doneStuff = true;
$(this).attr('href','https://concypt.com')
$(this)[0].click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Some Link
So I don't really know JQuery to well but in pure JS I think what you're looking for would look something like this.
document.querySelectorAll('a').forEach(function(a){
var dostuff = function(){
event.preventDefault();
alert('doing stuff');
// some_function();
alert('done');
this.removeEventListener('click',dostuff);
this.click();
}
a.addEventListener('click',dostuff);
});
Try this.
NOTE: You have to click the link twice. On first click it will do the stuff, and on second click it will do its default action.
var doneStuff = false;
$('a').on('click', function(event) {
if(doneStuff){
alert('done');
doneStuff = false;
return true;
}
event.preventDefault();
alert('doning stuff');
doneStuff = true;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Some Link
I want to capture browser close event using javascript. I googled but I am not getting any solution anywhere,below is my code where I have handled anchor, Form Submit and Submit button on onbeforeunload.
<script>
var validNavigation = false;
function wireUpEvents() {
window.onbeforeunload = function() {
if (!validNavigation) {
// invalidate session
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keydown', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>
Is there any way I can capture browser close button event, I have seen developers using X and Y axis but that is not recommended most of developers.
Thanks..
You can try this .. prompting user to confirm before closing tab. and you can do some thing you need
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>
I am looking into making a confirmation menu in JavaScript to where it will run a set of code depending if you select yes or no.
Now I want it to happen on the window.onbeforeunload event but only when the individual presses "yes" do I want the rest of the code to work. If they press "no" I want the window.onbeforeunload to be cancelled outright. I am wondering if it is at all possible and how. Here is what I have so far. The reason why I want this is because when I run the script the popup shows up on return but before someone would get to choose to stay or leave. The click(); feature starts up erasing the information. I want the .click(); to start up after someone presses "yes" on the return and only if they press "yes".
var validNavigation = false;
function wireUpEvents() {
var dont_confirm_leave = 0;
var leave_message = document.getElementById("kioskform:broswerCloseSubmit");
var leave_safari = document.getElementById("kioskform:broswerCloseSafari");
function goodbye(e) {
if (!validNavigation) {
function disp_confirm()
{
var leaveMessage=confirm("Are you sure you want to leave")
if (leaveMessage==true)
{ if (dont_confirm_leave!==1) {
if(!e) e = window.event;
//for IE
e.cancelBubble = true;
e.returnValue = leave_message.click();
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
//return works for Chrome and Safari
leave_safari.click();
return '';
//add the code to delete the kiosk information here.
// this is what is to be done.
}
}
else
{
Alert("Returning to the page.")
}
}
window.onbeforeunload=goodbye;
// Attach the event keypress to exclude the F5 refresh
jQuery('document').bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
jQuery("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
jQuery("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
jQuery("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
jQuery(document).ready(function() {
wireUpEvents();
});
Why not just use window.confirm?
I got to know how we can get a popup when the user tries to close the browser. Now my question how can we execute some piece of code if the user says 'Stay on page'? is there any click handler for that button?
Try using the onbeforeunload event.
(function () {
var oldMousemove = document.body.onmousemove,
onCancel = function () {
// Do something if the user stays.
document.body.onmousemove = oldMousemove;
};
window.onbeforeunload = function() {
document.body.onmousemove = onCancel;
return 'Do you really want to leave?';
};
})();
Note: Most browsers won't respect the custom prompt statement and will favor their own instead.
<script>
(function(){
window.onbeforeunload = function (e) {
if(!e) var e = window.event;
e.cancelBubble = true;
e.returnValue = false;
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
return false;
}
}());
</script>
Works in Firefox and IE 9
I would like to stop my event after sayHello1
var sayHello1 = function(e) {
console.log("hello1");
e.stopMe = true;
e.preventDefault(); // doesn't work
e.stopPropagation(); // doesn't work
return false; // doesn't work
};
var sayHello2 = function(e) {
console.log("hello2"); // Still fired !
if (e.stopMe ) console.log("stop hello2"); // works
};
document.addEventListener("click", sayHello1);
document.addEventListener("click", sayHello2);
"e.stopMe" cant help to stop sayHello2, but there is no way to do that ! (imagine firefox & Co using the name "stopMe" on their browser !)
You want to use e.stopImmediatePropagation() which prevents other listeners of the same event from being called.
var sayHello1 = function(e) {
console.log("hello1");
e.stopImmediatePropagation(); //keeps any event listener that is bound after this from firing
e.preventDefault(); // prevents the default action from happening
e.stopPropagation(); // prevents ancestors from getting the event
return false; // works like preventDefaut
};
var sayHello2 = function(e) {
console.log("hello2"); // Still fired !
};
document.addEventListener("click", sayHello1);
document.addEventListener("click", sayHello2);
<h1>Test</h1>