I want this link to have a JavaScript dialog that asks the user “Are you sure? Y/N”.
Link
If the user clicks “Yes”, the link should load, if “No” nothing will happen.
I know how to do that in forms, using onclick running a function that returns true or false. But how do I do this with an <a> link?
Inline event handler
In the most simple way, you can use the confirm() function in an inline onclick handler.
Link
Advanced event handling
But normally you would like to separate your HTML and Javascript, so I suggest you don't use inline event handlers, but put a class on your link and add an event listener to it.
Link
...
<script type="text/javascript">
var elems = document.getElementsByClassName('confirmation');
var confirmIt = function (e) {
if (!confirm('Are you sure?')) e.preventDefault();
};
for (var i = 0, l = elems.length; i < l; i++) {
elems[i].addEventListener('click', confirmIt, false);
}
</script>
This example will only work in modern browsers (for older IEs you can use attachEvent(), returnValue and provide an implementation for getElementsByClassName() or use a library like jQuery that will help with cross-browser issues). You can read more about this advanced event handling method on MDN.
jQuery
I'd like to stay far away from being considered a jQuery fanboy, but DOM manipulation and event handling are two areas where it helps the most with browser differences. Just for fun, here is how this would look with jQuery:
Link
...
<!-- Include jQuery - see http://jquery.com -->
<script type="text/javascript">
$('.confirmation').on('click', function () {
return confirm('Are you sure?');
});
</script>
You can also try this:
<a href="" onclick="if (confirm('Delete selected item?')){return true;}else{event.stopPropagation(); event.preventDefault();};" title="Link Title">
Link Text
</a>
I'd suggest avoiding in-line JavaScript:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
var check = confirm("Are you sure you want to leave?");
if (check == true) {
return true;
}
else {
return false;
}
};
}
JS Fiddle demo.
The above updated to reduce space, though maintaining clarity/function:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
return confirm("Are you sure you want to leave?");
};
}
JS Fiddle demo.
A somewhat belated update, to use addEventListener() (as suggested, by bažmegakapa, in the comments below):
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].addEventListener('click', reallySure);
}
JS Fiddle demo.
The above binds a function to the event of each individual link; which is potentially quite wasteful, when you could bind the event-handling (using delegation) to an ancestor element, such as the following:
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
function actionToFunction (event) {
switch (event.target.tagName.toLowerCase()) {
case 'a' :
reallySure(event);
break;
default:
break;
}
}
document.body.addEventListener('click', actionToFunction);
JS Fiddle demo.
Because the event-handling is attached to the body element, which normally contains a host of other, clickable, elements I've used an interim function (actionToFunction) to determine what to do with that click. If the clicked element is a link, and therefore has a tagName of a, the click-handling is passed to the reallySure() function.
References:
addEventListener().
Conditional ('ternary') operator.
confirm().
getElementsByTagName().
onclick.
if () {}.
Confirm OK, then goto URL (uses onclick())
jAplus
You can do it, without writing JavaScript code
<head>
<script src="/path/to/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="/path/to/jquery.Aplus.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
...
Link
...
</body>
Demo page
This method is slightly different than either of the above answers if you attach your event handler using addEventListener (or attachEvent).
function myClickHandler(evt) {
var allowLink = confirm('Continue with link?');
if (!allowLink) {
evt.returnValue = false; //for older Internet Explorer
if (evt.preventDefault) {
evt.preventDefault();
}
return false;
}
}
You can attach this handler with either:
document.getElementById('mylinkid').addEventListener('click', myClickHandler, false);
Or for older versions of internet explorer:
document.getElementById('mylinkid').attachEvent('onclick', myClickHandler);
Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:
document.body.onclick = function( e ) {
// Cross-browser handling
var evt = e || window.event,
target = evt.target || evt.srcElement;
// If the element clicked is an anchor
if ( target.nodeName === 'A' ) {
// Add the confirm box
return confirm( 'Are you sure?' );
}
};
This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.
USING PHP, HTML AND JAVASCRIPT for prompting
Just if someone looking for using php, html and javascript in a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.
<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>
the reason i used php code in the middle is because i cant use it from the beginning..
the code below doesnt work for me:-
echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";
and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.
Most browsers don't display the custom message passed to confirm().
With this method, you can show a popup with a custom message if your user changed the value of any <input> field.
You can apply this only to some links, or even other HTML elements in your page. Just add a custom class to all the links that need confirmation and apply use the following code:
$(document).ready(function() {
let unsaved = false;
// detect changes in all input fields and set the 'unsaved' flag
$(":input").change(() => unsaved = true);
// trigger popup on click
$('.dangerous-link').click(function() {
if (unsaved && !window.confirm("Are you sure you want to nuke the world?")) {
return; // user didn't confirm
}
// either there are no unsaved changes or the user confirmed
window.location.href = $(this).data('destination');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Nuclear code here" />
<a data-destination="https://en.wikipedia.org/wiki/Boom" class="dangerous-link">
Launch nuke!
</a>
Try changing the input value in the example to get a preview of how it works.
Related
I have a PHP script that generates links - I want to use addEventListener to pick up arguments on these links but what ever I try seems to fail.
It's very old code that used to work with onClick events but I'm updating the code and beleived that addEventListener is the way to go.
I've taken my code back to basics to test the best code solution.
So I have links like so
<a href="#" id="1" data-un-str="miguel" class="nameClick" >Alert Name1</a>
</br>
<a href="#" id="2" data-un-str="sarah" class="nameClick" >Alert Name 2</a>
</br>
and a function
function buildlink(e)
{
var e = window.e || e;
if (e.target.tagName !== 'A')
return;
alert(e.id);
}
and event handler like this.
window.onload=function(){
if (document.addEventListener)
document.addEventListener('click', buildlink, false);
The event handler works, and picks up the clicks on the links.
I just don't understand how to pick up the arg data in id, but most of all I'd like to know how to pick up the args in data-un-str too.
E.g. "miguel" or "sarah"
I presume it is possible as I've seen it done elsewhere, I just couldn't work out how it had been done. I used to code JS a lot more about 10+ years ago, but I'm a bit lost now on DOM stuff and things seem to have changed alot.
For the code above when it tries to alert the id of the link clicked I just get 'undefined' in my alert.
Any advice would be great. Thanks
The event.target (where event is the first parameter passed to the handler) will refer to the clicked element, and you can get the data-un-str attribute by checking the target's .dataset.unStr property:
function buildlink(event) {
const { target } = event;
if (target.tagName !== 'A') {
return;
}
const { id, dataset } = target;
const { unStr } = dataset;
console.log(id, unStr);
}
window.onload = function() {
if (document.addEventListener)
document.addEventListener('click', buildlink, false);
}
Alert Name1
<br>
Alert Name 2
<br>
I know that this question is been asked tons of times, but I'm asking not exactly that. This code belongs to website menu bar, so I have to keep this code, otherwise design would be totally different.
Code:
<li class="removable-parent">
<a class="removable-parent" href="http://88.88.209.56:12/player.html" data-
link-type="EXTERNAL" target= "_blank">
<span id="4884dd90" class="preview-element Link item-link magic-circle-
holder text-element custom" data-menu-name="PREVIEW_LINK" >Spiller</span>
</a>
<script>
function clickHandler() {
window.open(this.href, "_blank", "width=640,height=480");
return false; // to prevent default action.
} document.getElementById("http://88.88.209.56:12/player.html").onclick=clickHandler
}
</script>
</li>
So how can I make that this code opens window in decided size?
You will need to use javascript.
Get a reference to your object and handle the click event. In that event, use window.open with the proper parameters to set the width and height of your pop-up window.
Make sure you cancel the original event so you don't end up with two pop-ups.
Something like:
<script>
function clickHandler() {
window.open(this.href, "_blank", "width=640,height=480");
return false; // to prevent default action.
}
var elems = document.querySelectorAll(".removable-parent");
for (var i = 0, elem; elem = elems[i]; ++i) {
elem.onclick = clickHandler;
}
</script>
Or, if you wish to apply this behavior on one link, first add an id attribute to your link:
<a class="removable-parent" id="myelement" href="http://88.88.209.56:12/player.html" data-link-type="EXTERNAL" target= "_blank">
The script should then be simplified so it applies only on that element:
<script>
function clickHandler() {
window.open(this.href, "_blank", "width=640,height=480");
return false; // to prevent default action.
}
document.getElementById("myelement").onclick = clickHandler;
</script>
I've written a JavaScript code which over-ride the native alert() method.
I need to capture the HTML element which comprises the code of alert() execution.
First two cases are examples. I have printed the elements in console.log.
Case 1 - Capturing the <script> tag:
HTML: <script> alert(1); </script>
JS:
window.alert = function()
{
console.log(document.currentScript); // <script> is printed
}
Case 2 - Capturing the <img> tag:
HTML: <img src='1' onerror="alert(1)">
JS:
window.alert = function()
{
console.log(arguments.callee.caller.arguments[0].target);
// arguments.callee --> console.log()
// arguments.callee.caller --> onerror(event) {}
// arguments.callee.caller.arguments[0] --> event
// arguments.callee.caller.arguments[0].target --> <img>
}
Case issue - Capturing the <a> tag:
HTML: Click here for alert
JS:
window.alert = function()
{
console.log( // how to find <a> element)
}
Please don't suggest me to modify the HTML by including IDs for <a> or something similar. Consider that the HTML is purely static, and I can't modify anything. I can just add a JavaScript, and I just wan't to know how this can be done.
You might be able to find such alerts and convert them to click events. Something like this. Note the click event alert call could be made much more sophisticated and potentially use eval(), but i leave that for you to risk.
window.alert = (function(){
var selected = document.querySelectorAll("a[href^='javascript:alert('");
Array.from(selected).forEach(function(item){
var old = item.href
item.addEventListener("click", function(){ alert(old.substring(11)); });
item.href="javascript:void(0);";
});
var _alert = function(msg) {
console.log(msg);
console.log(arguments.callee.caller.arguments[0].target);
};
return _alert;
})();
test
You can use load event at window; click event at selector "a[href='javascript:alert(1);']" to get value of href attribute; call event.preventDefault() within click handler; String.prototype.match() to create array of values withing href attribute; define matches globally; new Function(); Function.prototype.call() to set this to <a> element; call .click() on selector : <a> element with matched parameters returned by .match()
window.alert = function() {
console.log(arguments, this)
}
window.addEventListener("load", function() {
a = document.querySelector("a[href='javascript:alert(1);']");
a.addEventListener("click", function(event) {
event.preventDefault();
var data = this.href.replace(/javascript/, "");
matches = data.match(/\w+(?=\()|(\(.*\))/g);
matches[1] = matches[1].replace(/\(|\)/g, "");
var fn = new Function(matches[0] + ".call(a, matches[1])");
fn();
});
a.click();
});
Don't use the href attribute to call JavaScript. It should be avoided. It is not recommended usage. Use the onclick event instead. See here: https://stackoverflow.com/a/10242595/5969411
<script>
window.alert = function(msg, element) {
console.log('Msg:', msg);
console.log('Element:', element);
};
</script>
Test 1
Test 2
Test 3
I've returned false from the onclick event above in order to repress the anchor from going to '#' URL directive, but you could easily return true instead here, if you wish.
I have a Sharepoint list where I want to customize the editForm.aspx page with Javascript.
The problem is that I can't manage to add any events to the controls in that page. I am able to get a reference to my control with this code:
var textarea1;
var objForm = document.forms[0];
function FindField() {
var title;
title= $().SPServices.SPGetDisplayFromStatic({ listName: "MyList", columnStaticName: "mycolumn" });
textarea1 = ChooseFieldByTitle("TextField", title);
}
function ChooseFieldByTitle(TypeField, title) {
var elem;
for (idx = 0; idx < objForm.elements.length; idx++) {
elem = objForm.elements[idx];
if (elem.id.indexOf(TypeField) != -1 &&
elem.title == title) {
return elem;
}
}
return null;
};
This runs fine but I can't attach any event on this control. I have tried the following code (Field is a textArea):
Field.attachEvent("onchange", myFunction);
Field.addEventListener("onchange", myFunction, false);
Field.onchange = myFunction() {};
When I change the content of the textArea nothings happen. When I debug with IE developers tools "myFunction" is never called. What am I doing wrong? I have look at SPServices JQuery library but nothing seems to be related to Javascript events.
Does anyone have a clue?
Try to use Jquery, this is a Javascript library that is used a lot. It makes for instance selecting objects easier. If you want to combine it with spservices (or another library), add the following lines in your aspx page under the PlaceHolderMain:
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
<script language="javascript" type="text/javascript" src="/SiteAssets/js/jquery-1.9.0.js"></script>
<script language="javascript" type="text/javascript" src="/SiteAssets/js/jquery.SPServices-0.7.2.min.js"></script>
<script language="javascript" type="text/javascript" src="/SiteAssets/js/myjavascriptfile.js"></script>
You can then select objects on your page via jquery and immediately tie to the events e.g.:
$(":input[title$='atitleofsomefield']").keyup(function() {
// do stuff
})
Here is a list of Jquery events: http://api.jquery.com/category/events/
The "onchange" event is fired by a dropdown box when you select a new value. It won't fire for a Textarea. In your case you may want to check the KeyUp event for example, or the Blur event.
Also, you may want to use jQuery or another library to handle the events.
The only way that I have found to accomplish this is via a timer. Look at something like this:
$(document).ready(function() {
var initialValue = undefined;
Field.on('change', function(){
//If the value has changed, run the function
if(initialValue==undefined || Field.val()!=initialValue){
initialValue = Field.val();
myFunction();
});
//Reinitialize the timer
checkForChange();
});
//Timer function to throw the 'changed' event
function checkForChange() {
setTimeout(triggerChange, 1500);
}
//Send the changed event for Field
function triggerChange(){
Field.trigger('change');
}
And then within your function you do your regular logic.
In my page I have many edit buttons each name starts with "edit" and then some id. I want to know any of my edit buttons is clicked or not.
In details, I have form. In form I have many edit buttons which name starts with "edit" , delete buttons which name starts with "delete" and 1 add button. All are submit buttons. form onsubmit I call JavaScript function in which I want if the button is edit confirm("some text") else submit form.
How can I do that in JavaScript?
I think give all these buttons same id and then getElementById but then how con I change?
This is simple using jQuery:
$(':button').click(function() {
// reference clicked button via: $(this)
var buttonElementId = $(this).attr('id');
});
Try it out:
http://jsfiddle.net/7YEay/
UPDATE based on feedback in comments
This is untested/pseudo code:
$(':submit').click(function(event) {
var buttonName = $(this).attr('name');
if (buttonName.indexOf('edit') >= 0) {
//confirm("some text") logic...
}
event.preventDefault();
});
This documentation may be helpful too: http://api.jquery.com/submit/
function MyOnSubmit(e){
e = e || window.event;
// srcElement for IE, target for w3c
var target = e.target || e.srcElement;
if (target.id.indexOf("edit") > -1){
// an edit button fired the submit event
}
}
although i advice you research further to find a better way to handle edit and delete buttons (like making them links with href=editpage.jsp?id=23)
I'm pretty sure you just answered this yourself...
Each starts with "edit", and ends with a unique ID?
So... $(button).attr("id") would give you that. Store it in a variable? Not sure what you're trying to do..
bind click event on all button:
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
if (button.addEventListener) {
button.addEventListener('click', handler, false);
}
else {
button.attachEvent('onclick', handler);
}
}
in your event handler, get the Event object, and then get the target:
function handler(e) {
e = e || window.event;
// srcElement for IE, target for w3c
var target = e.target || e.srcElement;
var id = target.name.substring(4);
/* your code rely on id */
}
I think you might not have phrased your question correctly. If you are using jquery, locating the button is as easy as $('#id'), and if you want to store any information on that button, you can either add an attribute or use jquery.data function.
$('#id').attr("pressed", "true");
Or
$('#id').data('pressed', 'true');