javascript popup alert on link click - javascript

I need a javascript 'OK'/'Cancel' alert once I click on a link.
I have the alert code:
<script type="text/javascript">
<!--
var answer = confirm ("Please click on OK to continue.")
if (!answer)
window.location="http://www.continue.com"
// -->
</script>
But how do I make it so this only runs when clicking a certain link?

You can use the onclick attribute, just return false if you don't want continue;
<script type="text/javascript">
function confirm_alert(node) {
return confirm("Please click on OK to continue.");
}
</script>
Click Me

Single line works just fine:
<a href="http://example.com/"
onclick="return confirm('Please click on OK to continue.');">click me</a>
Adding another line with a different link on the same page works fine too:
<a href="http://stackoverflow.com/"
onclick="return confirm('Click on another OK to continue.');">another link</a>

just make it function,
<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>
click me

In order to do this you need to attach the handler to a specific anchor on the page. For operations like this it's much easier to use a standard framework like jQuery. For example if I had the following HTML
HTML:
<a id="theLink">Click Me</a>
I could use the following jQuery to hookup an event to that specific link.
// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {
// The '#theLink' portion is a selector which matches a DOM element
// with the id 'theLink' and .click registers a call back for the
// element being clicked on
$('#theLink').click(function (event) {
// This stops the link from actually being followed which is the
// default action
event.preventDefault();
var answer confirm("Please click OK to continue");
if (!answer) {
window.location="http://www.continue.com"
}
});
});

Related

How to avoid "about:blank" while doing form action with javascript? [duplicate]

I have links like this:
<a href="#" onclick="myfunc({a:1, b:'hi'})" />click</a>
<a href="#" onclick="myfunc({a:3, b:'jo'})" />click</a>
And I would like to do a preventDefault() inside myfunc(), because a # will be added in the address bar when clicking on the link
(without doing return false; or href='javascript:void(0);')
Is this possible?
Can I get the event inside myfunc()
I believe you can pass in event into the function inline which will be the event object for the raised event in W3C compliant browsers (i.e. older versions of IE will still require detection inside of your event handler function to look at window.event).
A quick example.
function sayHi(e) {
e.preventDefault();
alert("hi");
}
Click to say Hi
Run it as is and notice that the link does no redirect to Google after the alert.
Then, change the event passed into the onclick handler to something else like e, click run, then notice that the redirection does take place after the alert (the result pane goes white, demonstrating a redirect).
The simplest solution simply is:
<a href="#" onclick="event.preventDefault(); myfunc({a:1, b:'hi'});" />click</a>
It's actually a good way of doing cache busting for documents with a fallback for no JS enabled browsers (no cache busting if no JS)
<a onclick="
if(event.preventDefault) event.preventDefault(); else event.returnValue = false;
window.location = 'http://www.domain.com/docs/thingy.pdf?cachebuster=' +
Math.round(new Date().getTime() / 1000);"
href="http://www.domain.com/docs/thingy.pdf">
If JavaScript is enabled, it opens the PDF with a cache busting query string, if not it just opens the PDF.
Try this:
<script>
$("a").click(function(event) {
event.preventDefault();
});
</script>
Can you not just remove the href attribute from the a tag?
<script type="text/javascript">
$('a').click(function(){
return false;
});
<script>
Add a unique class to the links and a javascript that prevents default on links with this class:
<a href="#" class="prevent-default"
onclick="$('.comment .hidden').toggle();">Show comments</a>
<script>
$(document).ready(function(){
$("a.prevent-default").click(function(event) {
event.preventDefault();
});
});
</script>
I think when we use onClick we want to do something different than default. So, for all your links with onClick:
$("a[onClick]").on("click", function(e) {
return e.preventDefault();
});
Simple!
onclick="blabla(); return false"
You can access the event from onclick like this:
<button onclick="yourFunc(event);">go</button>
and at your javascript function, my advice is adding that first line statement as:
function yourFunc(e) {
e = e ? e : event;
}
then use everywhere e as event variable
Without any JS library or jQuery.
To open a nice popup window if possible. Fails safely to normal link open.
...
And the helper function:
function openNewWindow(event, location) {
if (event.preventDefault && event.stopImmediatePropagation) {
event.preventDefault();
event.stopImmediatePropagation();
} else {
event.returnValue = false;
}
window.open(location, 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=800,height=450');
}
e.preventDefault();
from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
Or have return false from your method.

Avoid a link to reload the page in Javascript

I am having this button in an <a> tag (would like to keep it in an a tag).
<center>Change Password</center>
The problem is that when I hit Enter the password gets changed, unfortunately the page reloads, which would be very annoying, when it comes to UX. So, how can I fix this?
EDIT:
Well, I figuered out, that the problem is not the button, but the input.
Here the code:
<div id="login-box-field"><input type="password" id="new_password" placeholder="Password: " class="form-login myLink" title="Password" maxlength="20">
</div>
Well, some people say something about a Form and a JS script. Please, could you tell me, how to do that? Some other samples on the platform here didn't work :(
To prevent the reload of the page, you can use e.preventDefault() inside your function.
Check this out: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Example:
My HTML:
Click me
JS code:
var myLink = document.querySelector('.myLink')
myLink.addEventListener('click', function(e) {
e.preventDefault()
})
Replace anchor tag with button and add onclick() event then call the change passwaord method then it will work fine!
<div>
<center><button onclick="changePassword()" id="box_button" class="pw-button">Change Password</button></center></div>
<script>
function changePassword() {
alert("your code goes here")
}</script>
fiddle is here
you can use jquery prevent default action of a (if you don't want change your html) :
$("a").click(function(event){
event.preventDefault();
});
Update : if clicking password input result is page refresh, then you need to edit that function which this input calls , so edit that function to return false.
You need to prevent the default action of the link with event.preventDefault(). To prevent the link from doing anything, you should omit the href attribute or give it a href of javascript:void(0) or equivalently javascript:; and use the onClick event handler to perform the logic.
<center>Change Password</center>
<script>
function changePassword(e){
e.preventDefault();
console.log("Changing password");
//other logic
}
</script>
everyone.
I've found the solution, which worked for me:
<input class="tableInput" type="text" value="Table input" onkeypress="return tableInputKeyPress(event)" />
<script type="text/javascript">
function tableInputKeyPress(e){
e=e||window.event;
var key = e.keyCode;
if(key==13) //Enter
{
//do you task here...
return true; //return true to submit, false to do nothing
}
}
</script>
Again, thank you very much to everybody who posted his solution :)

Event click on href <a> tag [duplicate]

This question already has answers here:
How do I programmatically click a link with javascript?
(12 answers)
Closed 8 years ago.
I have a question about Javascript event here. I have an <a> tag like this:
<a id='aTag' href='http://example.com'>Click to redirect</a>
Then I call an event like:
<script>
$('#aTag').click();
//or
$('#aTag').trigger('click');
</script>
It does not redirect me to http://example.com. I tried to add an onClick() event in the <a> tag like this:
<a id='aTag' href='http://example.com' onclick='alert("Event happened");'>Click to redirect</a>
And then call the .click() event. It shows me alert("Event happened");
Can anyone show me how to call the .click() event correctly, or correct this redirect with issue with the href in that <a> tag?
In my business I just need an <a> tag, so not with the window.open or windown.location.
Explanation
Redirects can only happen if the user clicks directly on the link. Programmatic or deferred click triggers do not work.
An alternative would be:
to change directly the window.location
to open the link in a new tab/window
Changing window.location
window.location="http://wherever.you/want/to/g0";
or
window.location=$('a.selector').attr('href'); // to use a link's address
New tab/window
You cannot programmatically (click() or trigger) open new tabs/ windows or redirect. They get (ad-)blocked. automatically
So new tab/window openings always have to be triggered by user action. (Otherwise we'd always be full with popup ads)
So 1st of all, make sure that your js is executed on a user event, and then you should be able to use window.open.
JsFiddle example
html:
new tab google
<button class="user">user triggered</button>
<button class="programatic">programatic</button>
js:
$('a').on('click', function(e) {
console.log('clicked', e);
// unfortunately although we simulated
// the click on the <a/> , it will still
// not launch a new window - idk why.
// therefore we can use the line below
// to open the <a>'s href in a new tab/window
// NOTE: this will only occur if the execution was
// triggered by the user
window.open(e.currentTarget.href);
});
var simulateClick = function(origEv) {
var e = $.Event("click");
e.ctrlKey = true;
e.metaKey = true;
e.originalEvent = origEv;
$('a').trigger(e);
};
$('button.user').on('click', function(e) {
// this call will actually open a window
simulateClick(e);
});
$('button.programatic').on('click', function(e) {
// this will result in a blocked popup
$.get('/someurl').always(function() {
// executes the method after a non-user event
// results in blocked popup
simulateClick(e);
});
});
// this will result in a blocked popup
setTimeout(simulateClick, 1000);
Try this -
<a id="aTag" href="http://mylink.com" onclick="return doWork();">Click to redirect</a>
<script>
function doWork(){
//... do your works
return true; // then return true to redirect
}
</script>
Here is the fiddle - http://jsfiddle.net/gcJ73/
(Though the fiddle attributes are a little different to show you that it works)
or with jQuery:
//first assign the click handler
$('#aTag').click(function(){
//... do your work
return true;
});
//then call programmatically
$("#aTag").click(); or $("#aTag").trigger("click");
BTW programatically calling it will not redirect. Will just call the event handler, not redirect.
jQuery fiddle - http://jsfiddle.net/gcJ73/3/
Try:
<script>
jQuery('#aTag').click(function() {
// Your Code
});
</script>
jQuery('#aTag').click() does not execute the href attribute of an anchor tag so you will not be redirected, do:
$(document).ready(function() {
jQuery('#aTag').click( function (e) {
window.location.href = this.href;
});
});
<a id='aTag' href='http://mylink.com' onclick="location.href='http://mylink.com';">
Click to redirect
</a>
check this code snippet, also it will work like what you want to do.

The click event from javascript on a button doesn't fire

So, I was going through a tutorial on event handlers. I created a button as instructed and then when I click on it, I wanted an alert to be displayed. Thats it. But it wouldn't work. Here's my html code:
<button id="submit">Submit</button>
And here's my javascript code:
var myButton = document.getElementByID("submit");
myButton.onclick = function(){
alert("YOu clicked on this button");
}
I am using external js file and I've included it in the html from the head of the document.
document.getElementByID("submit"); -- it's Id instead of ID
Edit: I feel very bad for giving this one-liner as an answer, so to add to what others have said about learning how to use the browser's console as a debuggining tool, you should try to find an IDE/text editor with auto-completion to save you such headaches especially when you're just starting out.
You may have an issue where document.getElementById() is happening before the element is created on the page. Try including your JavaScript in an onload event, or include it after the button in your HTML.
As previously stated, use document.getElementById("submit") with lower case Id. Also, you may want to use setAttribute so the alert fires when the button is pressed instead of immediately opening a popup when the alert line is encountered.
<script language="javascript">
var myButton = document.getElementById("submit");
myButton.setAttribute("onclick", "alert('You clicked on this button')");
</script>
change from document.getElementByID to document.getElementById and make sure your script stay below all the elements in the body. Example:
<body>
<button id="submit">Submit</button>
<script type="text/javascript">
var myBtn = document.getElementById("submit");
myBtn.onclick = function()
{
alert("this is a click event button");
};
</script>
</body>
or you can put the script inside the <head></head> by add this event below to your script:
function initialize()
{
// paste your code in here
}
document.addEventListener("DOMContentLoaded",initialize,false);
Hope it work!
it maybe a typo. It is getElementById not ID

javascript/jquery simulate anchor "tel" click

I have found lots of messages about simulating an anchor click with javascript. Most using the "location" function, which doesn't work for me because I do not want to redirect anywhere. My anchor has href="tel:..." to invoke the iphone's phone function.
I can't have an anchor for clicking, so I wanted to have javascript/jquery simulate that click when a user presses a button, for example. How could I do this (if, indeed, it is even possible)?
Thanks
You can trigger the click event for the anchor on on the click of the button
$('#button1').on('click', function() {
$('#anchor1').click(); // triggering the click event on click of the button
});
Check this FIDDLE
$(function() {
$('a').on('click' , function() {
alert('Fired using button !!')
});
$('#button1').on('click' , function() {
$('a').click();
alert('Button Clicked !!')
});
});​
Try this:
$(your_button).trigger('click')
You could just trigger the click event...
$("a.phonenumber").click();
Here is a simple example of how to accomplish this -
$(function(){
$("#b1").on('click',function(){
alert("pressed b1!");
});
$("#b2").on('click',function(){
$("#b1").trigger('click');
alert("pressed b2!");
});
});​
Clicking on the first b1 button will trigger an alert. When clicking the second b2 button, first we "trigger" a click event on the first button (which will execute it's alert), and then alert the second value.
DEMO
I know the questions asks not to use the location function, but please try this out:
HTML:
<button class="click-to-call" data-phone="2125551234">call</button>
jQuery:
(could easily be written with only javascript too if you wanted to)
$('.click-to-call').on('click',function(){
window.location.assign('tel:'+ $(this).data('phone'));
});

Categories