Overriding default behavior of links using JQuery and JavaScript - javascript

I'm trying to override all 'a' tags in a document with a specific class to prevent their default behavior and send a javascript alert. Here is my code so far:
$('.specific-class').click(function (event) {
event.preventDefault();
event.onclick('alert("hello world")');
});
This code stops the links from firing, as it should, but it doesn't send my 'hello world' message.
Does anyone know the appropriate syntax to make the alert fire when the links are clicked? Let me know if I can provide any additional information!

Your error was using event.onclick(); instead of just alert() which will fire when you click
Here is the snippet:
$('.specific-class').click(function (e) {
e.preventDefault();
alert("hello world");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="specific-class">hi you, click me.</div>

Use alert inside handler as this function will be executed on the click of anchor.
$('.specific-class').click(function (event) {
event.preventDefault();
alert("hello world");
});
Or you can also update the onclick attribute value on page load
$(document).ready(function() {
$('.specific-class').attr('onclick', 'alert("Hello World!"); return false;');
});

Related

Create Back browser event using Jquery

I want to create a back button browser event using jquery. I did this code but it doesnt appear to work
$(document).ready(function() {
$('.back').click(function() {
window.history.back();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Back
The href="#" will add a new item to history, so window.history.back(); will "return" to the page where the link was clicked. You need to prevent the link from directing to # with this:
$( document ).ready(function() {
$('.back').click(function(e) {
e.preventDefault();
window.history.back();
});
});
you are missing to specify event as function argument, try this one..
$(".back").click(function(event) {
event.preventDefault();
history.back(1);
});
This might solve your problem.

href called issue in onclick function [duplicate]

If I have this element:
Item
How can I make both href and onClick work, preferably with onClick running first?
You already have what you need, with a minor syntax change:
Item
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow the `href` property to follow through or not
}
</script>
The default behavior of the <a> tag's onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn't return false, canceling the event (or the event hasn't been prevented)
Use jQuery. You need to capture the click event and then go on to the website.
$("#myHref").on('click', function() {
alert("inside onclick");
window.location = "http://www.google.com";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click me
To achieve this use following html:
Item
<script>
function make(e) {
// ... your function code
// e.preventDefault(); // use this to NOT go to href site
}
</script>
Here is working example.
No jQuery needed.
Some people say using onclick is bad practice...
This example uses pure browser javascript. By default, it appears that the click handler will evaluate before the navigation, so you can cancel the navigation and do your own if you wish.
<a id="myButton" href="http://google.com">Click me!</a>
<script>
window.addEventListener("load", () => {
document.querySelector("#myButton").addEventListener("click", e => {
alert("Clicked!");
// Can also cancel the event and manually navigate
// e.preventDefault();
// window.location = e.target.href;
});
});
</script>
Use a <button> instead. In general, you should only use a hyperlink for navigation to a real URL.
We can style a button to look like an anchor element.
From https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#onclick_events
Anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events .
These bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers.
Use ng-click in place of onclick. and its as simple as that:
Item
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow
// the`href` property to follow through or not
}
</script>

Jquery .on('click,'button' not working

I need to check if user closed browser. There is no reliable way, but the most accurate way seems to use onbeforeunload and check if a link or a button was clicked. I will also add f5 and some other extra checking.
But I have problem with button. If I click button, ajax call will be made even if there is if(window.link_was_clicked==false) condition.
<button onclick="setLocation('http://dev.site.com/checkout/')" class="button" title="Checkout" type="button"><span><span>Checkout</span></span></button>
And script:
jQuery(document).on('click', 'button', function(event) {
window.link_was_clicked= true;
});
window.onbeforeunload = function() {
if(window.link_was_clicked==false){
//make ajax call
}
};
It seems the problem is because there is setLocation function attached to button onclick. Is there any way to trigger jQuery(document).on first?
That variable doesnt exist on before load. so add it on the top and try again
window.link_was_clicked=window.link_was_clicked||false;
jQuery(document).on('click', 'button', function(event) {
window.link_was_clicked= true;
});
window.onbeforeunload = function() {
if(window.link_was_clicked==false){
//make ajax call
}
};
Since you haven't provided the code for setLocation(), I'll assume that that's where the problem is. Now, regarding a change to the order of execution of your click event handlers:
It is in general bad to have both embedded onclick and jquery-bound handlers, it leads to all sorts of confusion. If you can't change the html, however, you could do what this guy suggests: https://stackoverflow.com/a/7507888/2685386
$(document).ready(function() {
var myClick = $('button').attr('onclick');
$('button').removeAttr('onclick');
$(document).on('click', 'button', function(e) {
window.link_was_clicked=true;
// do my other stuff here....
eval(myClick);// this will now call setLocation()
});
});

jQuery selector click function clarification

Theres a gap in my understanding that i'd liked filled;
I have a basic jQuery click function like this..
$('.cl').each(function(e)
{
alert('works');
$(this).click(function()
{
alert('no works');
});
});
My HTML is like this:
<body>
<div id='c0'>
<div class='bO cl'>Button</div>
</div>
</body>
Basic stuff.
The 'works' alert is fired ok - but with the click function nothing happens - 'no works' is not fired.
Also
$('.cl').click(function()
{
alert('help');
});
Does not work. Simple stuff i'm sure but i'm missing something.
Why is this?
One thing to make sure is that you run the event handler once the DOM and jQuery are initialized, which is by doing this:
$(function() {
$('.cl').click(function()
{
alert('help');
});
});
Also alternatively, if your cl is loaded after the fact such as by an Ajax call you can alternativley do this
$("body").on("click", ".cl", function() {
// Your code here
})
This registers the click event with the body but only gets dispatched if the actual target is of type cl.

Javascript onclick function trouble

I'm using a popover in bootstrap, and I want it to close when the user clicks anywhere else on the screen. The code I have is this:
$('#popover').bind('click', function() {
$(".popover").live('click', function(){ return false; });
$(document).one("click", function() {
alert('click');
});
});
The problem is that the click on the button is triggering the alert. For some reason javascript uses that click to start the function and trigger the click event inside of it. What am I doing wrong?
EDITED:
This code doesn't do anything:
$(".popover").live('clickoutside', function(){
alert('click');
});
Check out these:
https://developer.mozilla.org/en-US/docs/DOM/event.stopPropagation
https://developer.mozilla.org/en-US/docs/DOM/event.stopImmediatePropagation
If your .popover is inside #popover, you're triggering events from all the affected elements.
NOTE: jQuery's live is in deprecating process, use the alternatives:
http://api.jquery.com/on/
http://api.jquery.com/delegate/

Categories