Disable href after one click - javascript

I'm trying to disable an html link after one click.
I found some solutions but it seems that they doesn't work on my code.
Here is what I tried to do:
<html>
<script type="text/javascript">
function image(url)
{
var img = document.createElement("IMG");
var url = "http://www.luigimelisi.com/wp-content/uploads/2014/03/url_routing.jpg";
img.src = url;
document.getElementById('image').appendChild(img);
}
function clickAndDisable(link)
{
link.onclick = function(event)
{
e.preventDefault();
}
}
</script>
<body>
<div id="image"></div>
<div>Click Here</div>
</body>
</html>
How can I fix it?

In your clickAndDisable function and the onclick handler, the event (in this case 'e') is not being passed as a parameter. You pass in 'event' but reference 'e'. You can make this work by changing 'e' to 'event'. This is what your code might look like for that to work:
link.onclick = function(event) {
event.preventDefault();
};

Actually, your code will work in the way you are hoping. You just made a typo. The mistake you made is in the function 'clickAndDisable' you handle an event by passing in a parameter 'event', but then you try to utilize the event by calling e.preventDefault.
to fix, change e.preventDefault() to event.preventDefault()
Here is the working code or test on JSFiddle here: https://jsfiddle.net/y6ktL4af/
<html>
<script type="text/javascript">
function image(url)
{
var img = document.createElement("IMG");
var url = "http://www.luigimelisi.com/wp-content/uploads/2014/03/url_routing.jpg";
img.src = url;
document.getElementById('image').appendChild(img);
}
function clickAndDisable(link)
{
link.onclick = function(event)
{
event.preventDefault();
}
}
</script>
<body>
<div id="image"></div>
<div>Click Here</div>
</body>
</html>

I think you can fix this by removing the href property of the a tag, and then modifying the clickAndDisable() function to do something like:
link.onclick = null;
image();

There are several ways to solve this with disabling or hiding the link but a reusable one would be to attach an event handler to all links that should be clicked only once:
var oneClickEls = document.querySelectorAll('[data-allow-one-click="true"]');
var _i, _len, _el;
for ( _i = 0, _len = oneClickEls.length; _i < _len; _i++ ) {
_el = oneClickEls[_i];
_el.hasBeenClicked = false;
_el.addEventListener('click', function(event) {
if (this.hasBeenClicked) {
event.preventDefault();
return;
}
this.hasBeenClicked = true;
});
}
This will allow us to specify which links should only be clicked one in the html by adding an attribute named data-allow-one-click:
Click Here
Here is a js fiddle showing your code working: https://fiddle.jshell.net/1akdp6sp/

A possible method would be to change the onclick statement in the a element to something like:
onclick="this.href=''"
This changes the href of the hyperlink to nothing, so nothing happens when the link is clicked on. It also obviates the need for the clickAndDisable function. Is that what you mean by disabled?

Related

Stoping a link from executing it's href path

Hi I am trying to stop a link from executing it's default action , but I seem to have no luck.Here is my code:
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
});
var lightbox = {
init : function(actionString){
$("<div id='lightbox-background'></div>").appendTo("body");
$("<div id='lightbox'></div>").appendTo("body");
$("<p></p>").appendTo("#lightbox");
$("<a href='#' id='ok'>OK</a>").appendTo("#lightbox");
$("<a href='#' id='cancel'>Cancel</a>").appendTo("#lightbox");
}
}
I hoped that if I used e.preventDefault it would stop the link from from going to it's href path but it did not work.Am I doing something wrong?
EDIT: I just noticed that if I remove the call for the lightbox object from the click event handler the e.preventDefault() works.
Your problem is in this line:
var lightbox = $("#lightbox");
in onclick callback function hide
variable name is the same as name of global lightbox object defined outside click callback. Local variable mentioned above simply override global variable inside that function scope. Basically, you are calling init of $("#lightbox"):
$("#lightbox").init("....")
Not sure what are you doing, but try to update your code like this:
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightboxElement = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
});
Besides, calling
var container = $("#lightbox-background");
var lightboxElement = $("#lightbox");
at the first time, you will get an empty set of elements as init method is not executed at that moment and elements you are looking for are not created yet.
Try if it works
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
return false;
});
Have you tried it above the vars declared:
$("a.delete").on("click", function (e) {
e.preventDefault();
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
});
Just noticed that you have missed a ';' at closing here:
var lightbox = {
init : function(actionString){
$("<div id='lightbox-background'></div>").appendTo("body");
$("<div id='lightbox'></div>").appendTo("body");
$("<p></p>").appendTo("#lightbox");
$("<a href='#' id='ok'>OK</a>").appendTo("#lightbox");
$("<a href='#' id='cancel'>Cancel</a>").appendTo("#lightbox");
}
}; //<----this one
Example for a link like:
google
use javascript with jQuery
$("a").click(function(e){e.preventDefault(); return false;});
this will not redirect any link on the page :)
or in given case it will be like
$("a.delete").click(function(e){e.preventDefault(); return false;});
Note: Added e.preventDefault(); to prevent the event from triggering.

Override javascript click event one time

I would like to replace the default action of an click event for all anchors in a webpage.
When I use this piece of code:
<html> <head> <script>
var list=document.getElementsByTagName("a");
var isChecked = false;
function load () {
for (i=0; i<list.length; i++)
{
var old = (list[i].onclick) ? list[i].onclick : function () {};
list[i].onclick = function () {
if( !isChecked)
{
test();
old();
}
else
old();
};
}
}
function test() {
alert("new action");
isChecked = true;
}
</script> </head>
<body onload="load();">
<a id="nr_1" onClick="alert('test');"> Anchor 1 </A>
<a id="nr_2" onClick="alert('test2');"> Anchor 2 </A>
</body> </html>
When I click an anchor I get the alert out of the test function and then the default function of the second anchor (even when I click the first anchor). When I then again click one of the two anchors I always get the Alert from the second anchor.
How do I put the original onclick functions back for each anchor element? When someone has an solution in jquery I would be glad as well.
EDIT
I was succesfull using this code:
function load()
{
$('a').attr('disabled', 'disabled');
$('a').click(function(e){
if($(this).attr('disabled'))
{
alert("new");
e.preventDefault();
$('a').removeAttr("disabled");
this.click();
}
});
}
On loading of the page this function is called giving all anchor elements a "disabled" attribute. After clicking the element the e.preventDefault() function disables the inline onclick function. Then I remove the "disabled" attribute and call the click function of the element again. because now the element doesn't have a "disabled" attribute only the default function is performed. I'm still open for "more elegant" solutions to this problem, but for now I'm a happy camper!
If you use jQuery you can combine a one-time handler with a persistent handler:
Documentation for .one() and .on()
Working Example: http://jsfiddle.net/Q8gmN/
Sample HTML:
<input type="button" id="click" value="click" />
​
Sample JavaScript:
button.one('click', function () {
console.log('one time function fired');
});
button.on('click', function () {
console.log('persistent function fired');
});
​

Unexpected reference to variable in anonymous function

The following JavaScript has some unwanted behaviour:
<html>
<script>
function AddEventListener(el, listener)
{
el.addEventListener ? el.addEventListener('click', listener) :
el.attachEvent('onclick', listener);
}
function Init(parent)
{
var span = document.createElement("span");
span.innerText = "Span1";
AddEventListener(span, function() { alert(span.innerText); } );
parent.appendChild(span);
var span = document.createElement("span");
span.innerText = "Span2";
parent.appendChild(span);
}
</script>
<body onload="Init(document.getElementById('drop'));">
<div id='drop'></div>
</body>
</html>
If you click on Span1, Span2 is shown in the alert window. I understand why: javascript variable scope. But I don't know how to solve it.
Some context: I used this.innerHTML which works fine except in IE8. this points to the window in IE8, not to the parent of the event listener.
Instead of using a global variable in your click callback, you can use the event parameter that is being passed to every event you register, and then use its event.target parameter to get the DOM element that participated in the event.
For that, you may change your event listener registering to: AddEventListener(span,function(event) {alert((event.target ? event.target : event.srcElement).innerText);});
I've set up an example of it using your code here: http://jsfiddle.net/dvirazulay/fTa6T/1/
You can return a function instead of just declaring one, but I like #Dvir Azulay suggestion better:
function CreateAlert(span)
{
return function() { alert(span.InnerText); };
}
function Init(parent)
{
var span=document.createElement("span");
span.innerText="Span1";
AddEventListener(span, CreateAlert(span));
parent.appendChild(span);
var span=document.createElement("span");
span.innerText="Span2";
parent.appendChild(span);
}
Try this: (changed the second definition of span to span2)
<!DOCTYPE html>
<html>
<script>
function AddEventListener(el,listener)
{
el.addEventListener ? el.addEventListener('click', listener) : el.attachEvent('onclick', listener);
}
function Init(parent)
{
var span=document.createElement("span");
span.innerText="Span1";
AddEventListener(span,function() {alert(span.innerText);});
parent.appendChild(span);
var span2=document.createElement("span");
span2.innerText="Span2";
parent.appendChild(span2);
}
</script>
<body onload="Init(document.getElementById('drop'));">
<div id='drop'></div>
</body>
</html>

How to display a confirmation dialog when clicking an <a> link?

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.

How can i dynamically Change onmouseover, onmouseout and onClick WITH parameters?

I have an image:
<img id="reqPic" src="mark.png" />
I also have declared a flag earlier on in the page:
<script type="text/javascript">
var isToolTipEnabled = true;
</script>
I now want to be able to check the flag and if its true, assign the onmouseover and onmouseout events. However, the onmousover event has to be changed to another function called Tip('string') which takes in a string. I have seen other questions on here on how to change this but it I dont see how I can pass paramters to the new function I want to change to.
The onClick would be changed to something like this:
onClick="javascript:toggleHelp('reftypeHelp');";
Any help on this would be greatly appreciated.
Thanks!
document.getElementById("reqPic").onmouseover = function() { Tip('This is the string.'); };
You could have an onload event on your body tag which calls a function that checks necessary values.
<script type="text/javascript">
var isToolTipEnabled = true;
function eventAdder() {
if (isToolTipEnabled) {
var img = document.getElementById('reqPic');
img.onmouseover = function() {
Tip('string');
}
img.onmouseout = whateverElse;
}
}
</script>
<body onload="eventAdder();">
with jQuery you could use the hover function but yeah creating an inline function works too

Categories

Resources