i want to disable my link when it is clicked .
checkletter is a function which checks if letter is available in word for my hangman game.
<span id="A">A</span>
i tried using this
a.visited{
display:none;
}
it doesn't seem to be working
Please advice!!
document.querySelector('#A a').style.pointerEvents = 'none';
** http://caniuse.com/#search=pointer-events
Can you just use your checkLetter function?
function checkLetter(letter) {
// Do stuff
document.getElementById(letter).style.display = "none";
}
update
To disable the link instead of hiding it (as requested in comment) see this link: http://jsfiddle.net/J67eY/1/
EDIT:
Very Fun Fiddle
Long story short: assuming link is assigned to your link:
link.href = null;
will disable the link entirely.
I got excited and posted too quickly. Here's what you want :)
var links = document.links || document.anchors || document.getElementsByTagName('a');
for (var i = 0, j = links.length; i < j; i++) {
addEvent(links[i], 'click', disable);
}
function disable(evt) {
var e = evt || window.event,
link = (e.currentTarget) ? e.currentTarget : e.srcElement;
checkLetter(link.innerHTML);
link.href = null;
return false;
}
function addEvent(element, myEvent, fnc) {
return ((element.attachEvent) ? element.attachEvent('on' + myEvent, fnc) : element.addEventListener(myEvent, fnc, false));
}
This code also assumes you removed javascript:checkLetter('A') from your link's href="". Instead, I call it inside the function using the letter that it is (link.innerHTML)
Related
I have this code I got it from an old post, but it doesn't seem to be working anymore please help. I can't even click on the links anymore, but my main goal is to have the user click on all the links and then have the page redirect to another page on my website.
<script>
window.onload = function () {
var anchors, clicked_count, clicked, i, cur_anchor, my_anchor_id;
anchors = document.getElementsByTagName("a");
clicked_count = 0;
clicked = {};
for (i = 0; i < anchors.length; i++) {
cur_anchor = anchors[i];
cur_anchor.setAttribute("link", i);
cur_anchor.onclick = function (e) {
e = e || window.event;
e.preventDefault();
my_anchor_id = this.getAttribute("link");
if (!(my_anchor_id in clicked)) {
clicked[my_anchor_id] = null;
if (++clicked_count === anchors.length) {
console.log("WOULD BE REDIRECTING");
//window.location.href = "facebook.com";
}
}
};
}
};
</script>
Some Text 1
Some Text 2
Some Text 3
First of all, fix your HTML you cannot have multiple the same id attributes as you got three times id="link". Please change it to class="link" to avoid problems.
Like this:
Some Text 1
Some Text 2
Some Text 3
If you are using jQuery, you can achieve what you described (that is redirecting after clicking three different links) with much simpler code.
Below is a example solution with comments, that will check which links were already clicked and redirect only if user click all three of them, no matter in what order he clicks them:
$(document).ready(function() {
// Create an array for clicked elements
var clicked = [];
// Create a click event for every link with class "link"
$('.link').click(function() {
// Check if we didn't clicked that link yet
if (clicked.indexOf($(this).attr('href')) === -1) {
// If we didn't add it's href attribute to "clicked" array"
clicked.push($(this).attr('href'));
}
// If number of clicked links is 3, redirect
if (clicked.length === 3) {
console.log('REDIRECT');
// location.href = 'http://put-your-url-here.com'
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Some Text 1
Some Text 2
Some Text 3
Please try it now
window.onload = function () {
var anchors, clicked_count, clicked, i, cur_anchor, my_anchor_id;
anchors = document.getElementsByTagName("a");
clicked_count = 0;
clicked = {};
for (i = 0; i < anchors.length; i++) {
cur_anchor = anchors[i];
cur_anchor.setAttribute("class", i);
cur_anchor.onclick = function (e) {
e = e || window.event;
e.preventDefault();
my_anchor_id = this.getAttribute("class");
if (!(my_anchor_id in clicked)) {
clicked[my_anchor_id] = null;
if (++clicked_count === anchors.length) {
window.location.href = this.getAttribute('href');
}
}
};
}
};
Some Text 1
Some Text 2
Some Text 3
window.onload = function () {
var anchors, clicked_count, clicked, i, cur_anchor, my_anchor_id;
anchors = document.getElementsByTagName("a");
clicked_count = 0;
clicked = [];
for (i = 0; i < anchors.length; i++) {
cur_anchor = anchors[i];
cur_anchor.setAttribute("link", i);
cur_anchor.onclick = function (e) {
e = e || window.event;
e.preventDefault();
window.location.href = "https://facebook.com";
}
}
};
I need to know if users clicked on an internal or external link to alert them.
I have many internal and external links on my site.
My internal links are like this:
about
draw graph
I need to alert only when external links are clicked.
(I've included two methods here: One method uses jQuery, and the other doesn't use jQuery. Skip down to the bold heading if you don't want to use jQuery)
One way you could do this is by adding a class to each external link, and then attaching an event handler to everything in that class which raises an alert when you click the link. That's tedious, though, as you have to add the class to every external link, and it won't for user generated content.
What you can do is use jQuery, along with the CSS selector a[href^="http"], to select all the external links, and then attach an event handler that raises your alert when they're clicked:
$('a[href^="http"]').click(function() {
alert();
});
a[href^="http"] means "an a tag which has a link, and that link has to start with 'http'." So here we select all the elements which start with http - that is, every external link - and then set it so that when you click on them, an alert pops up.
Non-jQuery method
If you want to do this without jQuery, you'll want to use document.querySelectorAll('a[href^="http"]') and bind the click event of each element in the array that that function returns. That looks something like this:
var externalLinks = document.querySelectorAll('a[href^="http"]');
for (var i = externalLinks.length-1; i >= 0; i--) {
externalLinks[i].addEventListener("click", function() { alert(); }, false);
}
I had to do this from scratch on my own site so I'll just copy + paste it here for you. It came from inside one of my objects so if I left some this keywords you can remove them.
function leaving() {
var links = document.anchors || document.links || document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if ((links[i].getAttribute('href').indexOf('http') === 0 && links[i].getAttribute('href').indexOf('fleeceitout') < 0) && (links[i].getAttribute('href').indexOf('/') !== 0 && links[i].getAttribute('href').indexOf('#') !== 0) && links[i].className.indexOf('colorbox') < 0) {
addEvent(links[i], 'click', this.action);
}
}
}
function action(evt) {
var e = evt || window.event,
link = (e.currentTarget) ? e.currentTarget : e.srcElement;
if (e.preventDefault) {
e.preventDefault();
} else {
window.location.href = link.href;
return;
}
var leave = confirm("You are now leaving the _______ website. If you want to stay, click cancel.");
if (leave) {
window.location.href = link.href;
return;
} else {
return leave;
}
}
var addEvent = function (element, myEvent, fnc) {
return ((element.attachEvent) ? element.attachEvent('on' + myEvent, fnc) : element.addEventListener(myEvent, fnc, false));
};
Replace instances of 'fleeceitout' with your sites domain name (microsoft.com, etc) and you're set.
The easiest ways are with jQuery, using a special class for external links, or by checking for "http://" in the URL.
Like this, if using a special class:
$("a.external").on("click", function() {
//de Do something special here, before going to the link.
//de URL is: $(this).attr("href")
});
And then in HTML:
<a href="http://external.link" class='external'>external link</a>
Or, you can check for http:// in the URL! Then you don't need a special class.
$('a[href=^"http://"]').on("click", function() {
//de Do something special here, before going to the link.
//de URL is: $(this).attr("href")
});
Cite: My original method of testing for "http://" was a bit slower, actually doing an indexOf test on .attr("href") so I used #Matthew's selector choice instead. Forgot about the caret route! Props to #Matthew on that, and for the non-jQuery alternative.
$(document).ready(function() {
$('a').click(function() {
var returnType= true;
var link = $(this).attr('href');
if ( link.indexOf('http') >= 0 ) {
returnType=confirm('You are browsing to an external link.');
}
return returnType;
});
});`
I have following URL in my few pages(http://something.com)..
Home
Index
About
Contact
Same
<a hre="http://example.com/home.html">New Home</a>
Services
and what I want is to convert all link to...
Home
Index
About
Contact
Same
<a hre="http://this.com/?url=http://example.com/home.html">New Home</a>
Services
So Basically I don't want to Convert "#" or "../" such link.
I am noob in JS.
From my effort, with the help of w3schools.. What i have tried to accomplish :-
<script type="text/javascript">
var url= document.getElementByTagName(a);
var pattern = /..\//g;
var result = pattern.test(url);
if(url.href != "#" || result === "false" ) {
var nurl = url.replace("http://this.com/?url="+url.href, url.href);
}
</script>
And I am not able to do anything... Please help, how can I modify URL and add http://this.com/?url=My_web_page_url_here.
UPDATE
I replaced my javascript with
<script type="text/javascript">
var links = document.links;
var i = links.length;
while (i--) {
if (links[i].href.slice(-1) == "#" ||
links[i].getAttribute("href").slice(0, 3) == "../") {
continue;
}
links[i].href = "http://this.com/?url=" + encodeURIComponent(links[i].href);
}
</script>
And still all url's are in the same way without append.
Try this...
var links = document.links;
var i = links.length;
while (i--) {
if (links[i].href.slice(-1) == "#" ||
links[i].getAttribute("href").slice(0, 3) == "../") {
continue;
}
links[i].href = "http://this.com/?url=" + encodeURIComponent(links[i].href);
}
jsFiddle.
I encoded the parameter, but if you don't want it encoded, like in your examples, drop the call to encodeURIComponent().
Another way to approach this is with event delegation. This method rewrites the URL at the point the link is used (and not before):
window.onload = function(){
var de = document.documentElement || document.body;
/// an event listener that steps in at the point the user has
/// clicked any element on the page. We specifically detect for
/// links and redirect the outcome
var proxyLink = function(e,t,href){
/// handle old versions of IE
e = e || Event; t = e.target || e.srcElement;
/// hashs can occur at the end of external links, so am only checking
/// your specific case. Switched to using getAttribute so as to get
/// the original href string.
if ( t.getAttribute('href').charAt(0) === '#' ) return;
if ( t.getAttribute('href').indexOf('../') === 0 ) return;
if ( String(t.nodeName).toLowerCase() == 'a' ) {
if ( e.preventDefault ) { e.preventDefault(); }
href = makeHrefAbsoluteIfPossible(t.href);
window.location = 'http://this.com/?url='+encodeURIComponent(href);
return (e.returnValue = false);
}
}
/// add the listener to the body or document element, this will trigger
/// the event onclick thanks to event bubbling.
if ( de.addEventListener ) {
/// handles modern browsers
de.addEventListener('click', proxyLink, true);
}
else {
/// handles old IE
de.attachEvent('onclick', proxyLink)
}
}
I've also create the following function to extend your hrefs to their absolute value based upon the current window.location. I'm never sure which browsers will return an absolute URL or the original href text, so this function is just incase the latter happens:
function makeHrefAbsoluteIfPossible( href ){
var path;
if ( href.indexOf(':') == -1 ) {
if ( href.charAt(0) == '/' ) {
path = href;
}
else {
path = String(window.location.pathname);
if ( path.indexOf('/') != -1 ) {
path = path.substring(0,path.lastIndexOf('/')) + '/';
}
path += href;
}
return window.location.protocol +'://' +
window.location.host + path;
}
return href;
}
Working example (with an alert instead of a redirect):
http://jsfiddle.net/teykz/2/
The benefits to this method are that it will work with applications that generate new html content during runtime... this most often happens with AJAX powered systems. Plus the links still appear as the original to the user (this can be desired depending on what you are doing).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Override default behaviour for link ('a') objects in Javascript
What is the best way for making entire page links in home page read only (non clickable like href=# or href="javascript:void()" based on a user action.
I wanted to use only Javascript and CSS to achieve this.
Only css
a {
pointer-events: none;
cursor: default;
}
try
with jquery
$("a").click(function() { return false; });
vanilla js
var elements = document.getElementsByTagName("a");
for (var i = 0; i < elements.length; i++) {
elements[i].onclick = function () { return false; }
}
Something like this should work
var anchors = document.getElementsByTagName('a');
for(var i=0,len=anchors.length;i<len;i++){
anchors[i].href = '#';
}
Here is a wonderful solution by CMS, by using event delegation technique.
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == 'A') {
someFunction(element.href);
return false; // prevent default action and stop event propagation
}
};
Demo
Start with:
links = document.getElementsByTagName('a')
Then:
for (var i=0; i<links.length; ++i) {
// disable a link, for instance like this
links[i].href = "javascript:void()"
}
jQuery
$("a").on("click",function(e) { e.preventDefault();
// anything you want to do on click
});
How about using replaceChild - it will work in all browsers since NS6/IE6/Chrome1/FX1 or so
DEMO
Plain JS:
window.onload=function() {
var anchors = document.getElementsByTagName('a');
for(var i=anchors.length-1;i>=0;i--){
var span = document.createElement("span");
span.innerHTML=anchors[i].innerHTML;
anchors[i].parentNode.replaceChild(span,anchors[i])
span=null;
}
}
Or my first suggestion in a comment on the page:
window.onload=function() {
var anchors = document.getElementsByTagName('a');
for(var i=anchors.length-1;i>=0;i--){
anchors[i].onclick=function() { return false }
}
}
I am thinking of to add a javascript function to capture all the <a> click events inside a html page.
So I am adding a global function that governs all the <a> click events, but not adding onclick to each (neither using .onclick= nor attachEvent(onclick...) nor inline onclick=). I will leave each <a> as simple as <a href="someurl"> within the html without touching them.
I tried window.onclick = function (e) {...}
but that just captures all the clicks
How do I specify only the clicks on <a> and to extract the links inside <a> that is being clicked?
Restriction: I don't want to use any exra libraries like jQuery, just vanilla javascript.
Use event delegation:
document.addEventListener(`click`, e => {
const origin = e.target.closest(`a`);
if (origin) {
console.clear();
console.log(`You clicked ${origin.href}`);
}
});
<div>
some link
<div><div><i>some other (nested) link</i></div></div>
</div>
[edit 2020/08/20] Modernized
You can handle all click using window.onclick and then filter using event.target
Example as you asked:
<html>
<head>
<script type="text/javascript">
window.onclick = function(e) { alert(e.target);};
</script>
</head>
<body>
google
yahoo
facebook
</body>
</html>
window.onclick = function (e) {
if (e.target.localName == 'a') {
console.log('a tag clicked!');
}
}
The working demo.
your idea to delegate the event to the window and then check if the "event.target" is a link, is one way to go (better would be document.body). The trouble here is that it won't work if you click on a child node of your element. Think:
<b>I am bold</b>
the target would be the <b> element, not the link. This means checking for e.target won't work. So, you would have to crawl up all the dom tree to check if the clicked element is a descendant of a <a> element.
Another method that requires less computation on every click, but costs more to initialize would be to get all <a> tags and attach your event in a loop:
var links = Array.prototype.slice.call(
document.getElementsByTagName('a')
);
var count = links.length;
for(var i = 0; i < count; i++) {
links[i].addEventListener('click', function(e) {
//your code here
});
}
(PS: why do I convert the HTMLCollection to array? here's the answer.)
You need to take into account that a link can be nested with other elements and want to traverse the tree back to the 'a' element. This works for me:
window.onclick = function(e) {
var node = e.target;
while (node != undefined && node.localName != 'a') {
node = node.parentNode;
}
if (node != undefined) {
console.log(node.href);
/* Your link handler here */
return false; // stop handling the click
} else {
return true; // handle other clicks
}
}
See e.g. https://jsfiddle.net/hnmdijkema/nn5akf3b/6/
You can also try using this:
var forEach = Array.prototype.forEach;
var links = document.getElementsByTagName('a');
forEach.call(links, function (link) {
link.onclick = function () {
console.log('Clicked');
}
});
It works, I just tested!
Working Demo: http://jsfiddle.net/CR7Sz/
Somewhere in comments you mentioned you want to get the 'href' value you can do that with this:
var forEach = Array.prototype.forEach;
var links = document.getElementsByTagName('a');
forEach.call(links, function (link) {
link.onclick = function () {
console.log(link.href); //use link.href for the value
}
});
Demo: http://jsfiddle.net/CR7Sz/1/
Try jQuery and
$('a').click(function(event) { *your code here* });
In this function you can extract href value in this way:
$(this).attr('href')
Some accepted answers dont work with nested elements like:
<font><u>link</u></font>
There is a basic solution for most cases:
```
var links = document.getElementsByTagName('a');
for(var i in links)
{
links[i].onclick = function(e){
e.preventDefault();
var href = this.href;
// ... do what you need here.
}
}
If anybody is looking for the typed version (TypeScript, using Kooilnc's answer), here it is:
document.addEventListener("click", (e: Event) => {
if(!e.target) { return; }
if(!(e.target instanceof Element)) { return; }
const origin = e.target.closest("a");
if(!origin || !origin.href) { return; }
console.log(`You clicked ${origin.href}`);
});
I guess this simple code will work with jquery.
$("a").click(function(){
alert($(this).attr('href'));
});
Without JQuery:
window.onclick = function(e) {
if(e.target.localName=='a')
alert(e.target);
};
The above will produce the same result.
Very simple :
document.getElementById("YOUR_ID").onclick = function (e) {...}
The selector is what you want to select so lets say you have button called
Button1
The code to capure this is:
document.getElementById("button1").onclick = function (e) { alert('button1 clicked'); }
Hope that helps.