Make all hyperlinks in the site do nothing - javascript

I want to make a script that disables hyperlinks and instead fires a function when one is clicked.
should work as
<a onclick="talk('http://google.com)'></a>
Is there a way to know when the wants to redirect and instead run "talk()" or display an alert window?

var anchors = document.getElementsByTagName('a');
for (var a = 0; a < anchors.length; a++){
anchors[a].href = "javascript:talk('" + anchors[a].href + "');";
}
Use some discretion though...

This solution uses (DOM Level 0) event handling instead of touching the href directly.
(function () {
var anchors = document.getElementsByTagName('a'),
i = anchors.length;
while (i--) {
anchors[i].onclick = function () {
talk(this.href);
return false;
};
}
}());
Edit: The benefit of this approach is it's much simpler to put the href back when you want to. Given an anchor tAnchor, you merely need to unset the onclick attribute:
tAnchor.onclick = null

Related

I've used setAttribute to modify the attributes of the <a> tag, but only partially. Why?

This is my code:
var links = document.querySelectorAll ("a");
for (let i = 0; i <links.length; i++) {
links[i].setAttribute("target", "_self");
}
My goal, obviously, is to have all the links open on the current page, but only some of them become _self and the rest remain _blank, why?
I'm providing you 2 ways to achieve what you want :
First code is what you provided, and the second one is an other way to add _self attribute value on links.
let links = document.querySelectorAll ("a");
for (let i = 0; i <links.length; i++) { //1st way
links[i].setAttribute("target", "_self");
}
links.forEach(link => { //2nd way
link.target = "_self";
});
<body>
Youtube
Google
Twitter
Netflix
</body>

append onclick to links javascript

To append:
_target="_blank"
To all links in an HTML page I use:
var links = document.querySelectorAll("a");
for (var i=0;i<links.length;i++) {
links[i].target="_blank";
}
But for some reason, when I use the exact same code and try to append:
onclick="alert(2)"
Like so:
var links = document.querySelectorAll("a");
for (var i=0;i<links.length;i++) {
links[i].onclick="alert(2)";
}
It does not work.
Can anyone show me how to do this? (preferably in javascript instead of jQuery)
thanks!
You can use your original query with a slight modification:
var links = document.querySelectorAll("a");
for (var i=0;i<links.length;i++) {
links[i].onclick=function() { alert(2) };
}
Try
links[i].onclick = function() { alert(2); };
As other answers show, the onclick property should contain a function. If you really want to assign a Javascript code string, you can do it with setAttribute.
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
links[i].setAttribute('onclick', "alert(2)");
}
Link 1
Link 2
Link 3
Link 4

Event target should be anchor but is image instead

I am working on a dialog script in Vanilla JS. I ran into a problem with the click event on the video image. Even tough the image is surrounded with an anchor tag it shows the image as the event.target on the "trigger-dialog-open" event.
Here is the HMTL:
<a class="trigger-dialog--open thumbnail" data-dialog-id="dialog-video" href="javascript:;">
<figure>
<img src="http://i.ytimg.com/vi/id/sddefault.jpg" alt="" />
</figure>
</a>
And this is the event in JS:
var openTriggers = document.getElementsByClassName('trigger-dialog--open');
for (var i = 0; i < openTriggers.length; i++) {
openTriggers[i].addEventListener("click", function (event) {
this.openDialog(event.target.getAttribute('data-dialog-id'));
}.bind(this), false);
}
The event handler wants to know the dialog-id from the anchors data attribute. It can't be found because it thinks the image is the event.target, not the actual anchor. How can I correct this? Thanks!
Use event.currentTarget. The event.target is supposed to be the img element since that is what the user has clicked on. The click then bubbles up through the image's containers. event.currentTarget gives you the element that the click handler was actually bound to.
(Or if you didn't bind this to some other object you could use this within the click handler and it should also be the current target.)
I have a few questions is the var openTriggers supposed to be a part of a module hash? Because if it's global then you don't use a this, you only add a this, if it's referencing a variable that the function is also contained in. For example:
var aThing = {
openTriggers: document.getElementsByClassName('trigger-dialog--open'),
openModal: null,
openDialog: function(clickedThingAttr){
if(this.openModal !== null){
this.openModal.style.display = 'none';
}else{
this.openModal = document.getElementById(clickedThingAttr);
}
this.openModal = document.getElementById(clickedThingAttr);
this.openModal.style.display = 'block';
},
setEventListenersNStuff: function(){
for (var i = 0, n = this.openTriggers.length;i < n; i++) {
this.openTriggers[i].addEventListener("click", function (event) {
this.openDialog(event.target.getAttribute('data-dialog-id'));
});
};
}
};//end of aThing hash object
aThing.setEventListenersNStuff();
There are a few issues here:
1. why are you using .bind I think that is a jQuery thing, you want to pass a string to another function when an object is clicked, there no need for binding at all.
2. Also make sure that if you want to do something like open a modal, there is no need to call another method unless it's kinda complex.
3. What about other potential dialogs, it seems that when a .trigger-dialog--open is clicked you're just showing that one one modal with the embedded id, but what about others? Make sure all modals are closed before you open a new one, unless you want to have like 10 modals are open.
A thing to note: I added the line var i = 0, n = openTriggers.length;i < n; i++, now in this case it's silly optimization, and I heard for modern browsers this doesn't apply, but to explain why I added it, is because i < openTriggers.length would count and integrate the array N times. (This may be an outdated optmiziation).
If you meant global
Below I added a different set of code, just in case you meant that var openTriggers is global, kinda like you wrote above. Also I used querySelectorAll for this which is like jQuery's $('.thing') selector.
anyhoo, I also added
var openTriggers = document.querySelectorAll('.trigger-dialog--open');
var n = openTriggers.length;
function openDialog(ddId){
for (var i = 0;i < n; i++) {
openTriggers[i].style.display = 'none';
};
document.getElementById(ddId).style.display = 'block';
};
for (var i = 0;i < n; i++) {
openTriggers[i].addEventListener("click", function (event) {
openDialog(event.target.getAttribute('data-dialog-id'));
});
}
}
So for the question of hiding already open modals I would suggest you could either cache the open Dialog within a module, or you could toggle a class, which would be less efficient since it would require an extra DOM search. Additionally you could add a if this.openModal.id === clickedThingAttr to hide if open, that way you got a toggle feature.
Anyways I suggest you read up on this stuff, if you want to use plain JS but would like the features of jQuery: http://blog.romanliutikov.com/post/63383858003/how-to-forget-about-jquery-and-start-using-native
Thank you for your time.
You can use a closure
var openTriggers = document.getElementsByClassName('trigger-dialog--open');
for (var i = 0; i < this.openTriggers.length; i++) {
(function(element) {
element.addEventListener("click", function (event) {
element.openDialog(event.target.getAttribute('data-dialog-id'));
}, false)
})(openTriggers[i]);
}

How to find links on a page, push them to array and open by each click 5 links from array?

I am looking for a way how to open few links in new tabs by one click.
Here is some HTML-code I wrote.
<ul>
<li>Google</li>
<li>Bing</li>
<li>Ebay</li>
<li>Amazon</li>
</ul>
<hr>
Open all links above by one click!
UPD: If it is possible, it would be great if it will search all links on a page wrapped with <li></li>, push them to array, and after a click link should open next 4 links from array.
jsFiddle example
Without questioning your motives (because you will be blocked by the popup blocker),
function open4links () {
var links = ['http://...', 'http://...', 'http://...', 'http://...'];
for (var i = 0; i < links.length; i++) {
window.open(links[i], '_blank');
}
}
(the a element).onclick = open4links;
Here, this works for me (based on the updated request): http://jsfiddle.net/R7qFv/4/
This keeps track of which links have been opened, so each time you click the link, it will open the next 4 in the list.
$("#openlinks").on("click", (function(){
var count = 0, nAtOnce = 4, $links = $("li a");
var openLinks = function(){
for (var i = 0; i < nAtOnce && count < $links.length; i++) {
window.open($links.eq(count++).attr("href"), '_blank');
}
};
return openLinks;
})());
I wrote it using jQuery because it's easier for me, but I'm sure you can translate if needed.
using window.open:
$('a').click(function(e) {
e.preventDefault();
$('li a').each(function(){
window.open($(this).attr("href"), '_blank');
});
});
As you can see in the JsFiddle, most browsers won't accept this because it is considered spam.
Use this to find all links in your html code and open in other window
<script type="text/javascript">
function OpenLinks(){
var arr = [];
$("#list a").each(function(){
arr.push(jQuery(this).attr("href"));
});
for(var i =0; i < arr.length;i++){
window.open(arr[i]);
}
}
</script>
obs: use jquery!

Greasemonkey - Find link and add another link

We have an internal inventory at work that is web based. I am looking at add a link say under a link on the page. There is no ID, or classes for me to hook into. Each link at least that I want to add something below it, starts with NFD. I basically need to pull the link text (not the link itself the text that appears to the end user) and use that in my url to call a web address for remoting in.
var links = document.evaluate("//a[contains(#href, 'NFD')]", document, null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i=0; i < links.snapshotLength; i++)
{
var thisLink = links.snapshotItem(i);
newElement = document.createElement("p");
newElement = innerHTML = ' Remote';
thisLink.parentNode.insertBefore(newElement, thisLink.nextSibling);
//thisLink.href += 'test.html';
}
Edit:
What I am looking for basically is I have a link NFDM0026 I am looking to add a link now below that using the text inside of the wickets so I want the NFDM0026 to make a custom link to call url using that. Like say a vnc viewer. The NFDM0026 changes of course to different names.
Here's how to do what you want (without jQuery; consider adding that wonderful library):
//--- Note that content search is case-sensitive.
var links = document.querySelectorAll ("a[href*='NFD']");
for (var J = links.length-1; J >= 0; --J) {
var thisLink = links[J];
var newElement = document.createElement ("p");
var newURL = thisLink.textContent.trim ();
newURL = 'http://YOUR_SITE/YOUR_URL/foo.asp?bar=' + newURL;
newElement.innerHTML = ' Remote';
InsertNodeAfter (newElement, thisLink);
}
function InsertNodeAfter (newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement)
parent.appendChild (newElement);
else
parent.insertBefore (newElement, targetElement.nextSibling);
}

Categories

Resources