Javascript to Replace HREF with ONCLICK - javascript

I'm new to Javascript, and need some help with creating a script that adds 'onclick' to href links of a particular class on an HTML page, upon page load - using the link's href URL, without touching the inline code. The script would modify a regular link, from this
<a href="URL" class="XYZ">
to this:
<a href="#" onclick="location.href='URL';" class="XYZ">
The URL changes for each link but the class remains the same. Here is what I got so far, but I was wondering if it can be improved:
window.onload = function() {
// Saving all links with XYZ-class in a variable
let links = document.getElementsByClassName('XYZ');
// Iterating through the links, changing the onclick attribute
for(let i = 0; i < links.length; i++) {
// Saving the URL
let grabbedURL = links[i].getAttribute('href');
// Putting it in onclick
links[i].setAttribute('onclick', `location.href='${grabbedURL}'`);
// Replacing href with '#'
links[i].setAttribute('href', '#');
}

Here's an approach using a for...of loop; you can change that if you want:
// iterate through all results of a css selector
for (let link of document.querySelectorAll('a.XYZ')) {
// set onclick attribute as text
link.setAttribute('onclick', 'location.href = ' + JSON.stringify(link.href) + ';');
// set href attribute to empty anchor (#)
link.href = '#';
}
<body>
http://example.com/
<br>
http://foo.bar/
</body>
There could be more modern solutions to your problem using EventTarget.addEventListener(), but so far that's what you requested. If you have a question to this answer please write a comment under it.
And as you new to Stack Overflow: If you had a helpful answer for your question, you can mark it as accepted. Of cause only if you want. Doesn't have to be mine.

Placing this in your JS should do it:
const convert = () => {
const links = document.querySelectorAll("a");
for(let i = 0; i < links.length; i++){
let href = links[i].getAttribute("href");
let handleClick = () => {
console.log("the url is:",href)
window.location.href = href;
}
links[i].onclick = handleClick;
links[i].setAttribute("href","#");
}
}
convert();

I think you might be missing a larger point here. An anchor is designed for navigation, if you want to change the destination, don't set an onclick and then disable the href, just update the href to where you want to go.
And, to do this in the simplest way, use event delegation, where we leverage the fact that events bubble up from their origin to the document. We just create one event handler on a common ancestor of all the elements in question and handle the even there. When we do, we check to see if the event originated at an element that we care about using event.target and if it did, we act accordingly.
Here's an example:
let url = "https://example.com";
// Set an event listener on the document itself
document.addEventListener("click", function(event){
// Check to see if the event originated at an
// element we want to handle.
if(event.target.nodeName === "A" && event.target.classList.contains("XYZ")){
// Just update the href of the element
event.target.href = url;
}
});
<p>Click the links below. Only the XYZ links will take you to example.com</p>
XYZ
abc
qrs
XYZ
zzz
XYZ
aaa
XYZ

If I'm understanding your question, I think you want something like this:
function updateLink() {
var link = document.getElementById("linkId");
link.setAttribute('href', "http://google.com");
}
Then just add an 'id' to your link. Or get the class rather than the id.

document.getElementsByClassName('XYZ')[0].setAttribute("onclick","location.href='URL' ")
Try this..
For after page load effect add script at the very end of your body tag

Related

Open all EXTERNAL links in a new tab - Shopify

I am trying to modify a site to make it open external links in a new tab.
Currently I have a loop which works fine except that it opens ALL links in a new tab which is not desired:
I have tried using filters but can't seem to get it to work properly.
<script>
document.addEventListener('DOMContentLoaded', function(){
let links = document.getElementsByTagName('a');
for(var i=0;i<links.length;i++){
links[i].setAttribute('target','_blank');
}
});
</script>
Maybe checking if the URL contains a Shopify handle or something along the line?
Thank you in advance!
You can check if the href attributes begins with http://, https:// or www. since those are the most common external links, all internal usually starts with /. (you can add an additional check if the href contains the domain name as well since it possible to have internal URL with the full URL)
So the code will become something like so:
document.addEventListener('DOMContentLoaded', function(){
const links = document.getElementsByTagName('a');
for(var i=0;i<links.length;i++){
const link = links[i];
const href = link.getAttribute('href');
if(href.match(/^((https?:\/\/)|(www\.))/) {
link.setAttribute('target','_blank');
}
}
});
Maybe something like this?
const links = document.querySelectorAll("a"); //get all <a> elements
links.forEach(el => { //loop trought all <a> elements
if(!el.href.includes(window.location.hostname)){ //if not this domain
el.setAttribute("target", "_blank");
}
})
/*just to show elements with target=_blank*/
[target="_blank"]{
color: green
}
other domain
this domain
Note: you don't need that document.addEventListener('DOMContentLoaded'... just put defer attribute on your <script> tag
To get only External links Open in new Tabs, you must use anchor’s property hostname, when its value not matching your “localhostname” string then overwriting anchor's property target default value "_self"(current browser content) to "_blank"(new tab) value, your script code will be:
<script>
document.addEventListener('DOMContentLoaded', function(){
let links = document.getElementsByTagName('a');
for(var i=0;i<links.length;i++){
if (links[i].hostname!="localhostname"){
links[i].setAttribute('target','_blank');
}
}
});
</script>

'onclick' Storing Value Not Working

so I have this <a> tag:
<a href="/book-testdrive" class="addtocart" value="YX57WDL" title="Book Test Drive">
<i class="glyphicon glyphicon-road"></i>
<span> Book Test Drive</span>
</a>
As you can see it is given a value of value="YX57WDL" now what I would like to do is capture that value when the a tag is clicked and placed into a variable.
There are many <a> tags on my page with many different values that are created dynamically. If a user presses another a tag I'd like it storing in the same variable but replace the value with that of the unique <a> tag value.
Also the variable needs to be stored site wide, I guess the solution to this would be Web Storage API.
So far I've tried using this Javascript:
var links = document.querySelectorAll('.addtocart ');
links.onclick = function(){
localstorage['storedValue'] = this.value ;
}
However when I console.log() the links variable it contains nothing.
Any idea why this might be happening?
Thanks
The problem is that document.querySelectorAll returns a (non-live) node list. This means that it is basically an array, so you could do a loop for each one instead:
for (var i = 0; i < links.length; i++) {
links[i].onclick = function(){
localStorage['storedValue'] = this.value ;
}
}
Also note that I changed localstorage to localStorage because it's case sensitive.
You will need to wait until the DOM is loaded, or else the call to document.querySelectorAll() will not find anything if the element you are looking for has not been added to the DOM yet.
I see you added jquery as a tag, so I assume you are using jquery. If that is the case, you can wrap your code with the jquery function to wait for the DOM to be ready, like this:
$(document).ready(function() {
var links = document.querySelectorAll('.addtocart ');
links.onclick = function(){
localStorage['storedValue'] = this.value ;
}
});
Also if you are using jquery, you could be using its on function to make this a lot simpler.
$(document).ready(function() {
$('.addtocart').on('click', function() {
localStorage['storedValue'] = this.value;
}
});
If you are not using jquery, see this question about how to wait for the DOM to load without the jquery $(document).ready() function.
Try ".getAttribute('value')" instead of ".value":
var links = document.querySelector('a.addtocart');
links.onclick = function(){
localStorage['storedValue'] = links.getAttribute('value');
}
Since you are using jQuery, you can do something like this:
$("body").on("click", ".addtocart", function(e) {
localstorage['storedValue'] = $(this).val();
});
You surely wonder why did your attempt fail. In fact, you were not too far from the solution, but you probably ran your script before your links were created. With the .on() function of jQuery you have a listener to the current and future elements matching the selector (which is ".addtocart").

Open specific links from a webpage with javascript?

I'm using Tampermonkey, and I can't seem to get jQuery to work on it so this has to be Javacript only.
I'm trying to get a script to open (in a new window) the link of an item on a webpage. I've got a list of items I need to open, here is an example of those items:
<a class="market_listings" href="http://blabla.com/item1">...</a>
<a class="market_listings" href="http://blabla.com/item2">...</a>
<a class="market_listings" href="http://blabla.com/item3">...</a>
etc.
As you can see, the item is defined by a class and an href. The class is not unique, but the href is.
I'm new to programming but this is my idea on how to open specifically those links from the page:
The script gets elements with class="market_listings",
just to narrow down the search of hrefs on the page.
The script looks if the href of those elements corresponds with
"http://blabla.com/item*"
The script opens a new window with that href.
I have pretty much 0 experience with coding, but this is how I'd start it, considering I only want to open items 1 and 3:
function gethrefandopenwindow() {
var items = document.getElementsByClassName('market_listings')
//don't know how to code from here
if (*a href of items corresponds to*: 'http://blabla.com/item1')
{
*open new window to href of item1*
}
if (*a href of items corresponds to*: 'http://blabla.com/item3')
{
*open new window to href of item3*
}
else {
*refresh the page and start over*
}
}
As I said, I have barely programming experience, so I don't know if this is possible, and if it is and you're willing to help, please explain it to me like I'm a TOTAL idiot/newbie. :)
The only other way I could think of is this one: Javascript getElement by href? ; Except I don't know how to apply it in my situation due to my noobiness (and how to open a specific href out of the elements).
Anyway, I hope you can help me,
Thank you!
It looks like you had the right idea. This function might get you moving in the right direction.
function OpenHrefsInNewWindow() {
//Get reference to your elements
var items = document.getElementsByClassName("market_listings");
for (var i = 0; i < items.length; i++) //Loop through your elements
{
//Verify that the href starts with http://blabla.com/item
if (items[i].href.indexOf("http://blabla.com/item") === 0)
{
//If it does, open that URL in a new window.
window.open(items[i].href, "_blank");
}
}
}
Another way to write it:
function OpenHrefsInNewWindow() {
//Get reference to your elements
var items = document.getElementsByClassName("market_listings");
var i = 0;
while(i < items.length) //Loop through your elements
{
//Verify that the href starts with http://blabla.com/item
if (items[i].href.indexOf("http://blabla.com/item") === 0)
{
//If it does, open that URL in a new window.
window.open(items[i].href, "_blank");
}
i++; //Increment i here.
}
}
Can retrive the url of link taking value of atribute and do ankthing later
Url = $(this).attr ('href')

anchor jumping by using javascript

I have a question that will be found very often. The problem is that nowhere can be found an explicit solution.
I have two problems regarding anchors.
The main goal should be to get a nice clean url without any hashes in it while using anchors to jump on a page.
So the structure of the anchors is:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<div class="wrap">
<a name="one">text 1</a>
<a name="two">text 2</a>
<a name="three" class="box">text 3</a>
</div>
Okay, if you will click one of the links the url will automatically change to
www.domain.com/page#1
At the end this should be just:
www.domain.com/page
So far, so good. Now the second thing is, when you search the internet for that problem you will find javascript as a solution.
I have found this function:
function jumpto(anchor){
window.location.href = "#"+anchor;
}
and calling that function with:
<a onclick="jumpto('one');">One</a>
what will be the same like before. It will add the hash to the url. I also added
<a onclick="jumpto('one'); return false;">
without success. So if there is someone who could tell me how to solve this I really would appreciate.
Thanks a lot.
You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.
Here is a lazier way to do that:
function jump(h){
var url = location.href; //Save down the URL without hash.
location.href = "#"+h; //Go to the target element.
history.replaceState(null,null,url); //Don't like hashes. Changing it back.
}
This uses replaceState to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:
function jump(h){
var top = document.getElementById(h).offsetTop; //Getting Y of target element
window.scrollTo(0, top); //Go there directly or some transition
}​
Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/
You can also use .scrollIntoView:
document.getElementById(h).scrollIntoView(); //Even IE6 supports this
(Well I lied. It's not complicated at all.)
I think it is much more simple solution:
window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"
This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.
I don't have enough rep for a comment.
The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).
Something to bear in mind if you don't have control of the document markup (e.g. webextension).
The location based method in the selected answer can also be simplified with location.replace:
function jump(hash) { location.replace("#" + hash) }
Because when you do
window.location.href = "#"+anchor;
You load a new page, you can do:
One
<script>
function getPosition(element){
var e = document.getElementById(element);
var left = 0;
var top = 0;
do{
left += e.offsetLeft;
top += e.offsetTop;
}while(e = e.offsetParent);
return [left, top];
}
function jumpTo(id){
window.scrollTo(getPosition(id));
}
</script>
I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>
On the .js file I have
function myFunction() {
var input = prompt("list or new or quit");
while(input !== "quit") {
if(input ==="test100") {
window.location.hash = 'test100';
return;
// else if(input.indexOf("test100") >= 0) {
// window.location.hash = 'test100';
// return;
// }
}
}
}
When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
Test link
which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ☺
The first suggested solution of accepted solution did not work for me entirely. The main problem was when it was already jumped to hash, and hash already in url, jump did not happen again. I propose here, for the sake of completeness, somewhat more elaborate solution which works (tested in Chrome and FF). el is element with anchor tag.
el.addEventListener('click', function(ev) {
ev.preventDefault();
const href = ev.target.getAttribute('href');
const hashIndex = href.indexOf('#');
if (hashIndex !== -1) {
const hashPart = href.substring(hashIndex);
if (location.hash === hashPart) {
document.querySelector(hashPart).scrollIntoView();
}
else {
location.hash = hashPart;
}
}
})

Change link targets

Is there a way (I assume it would be with javascript) that I can have a checkbox or link on my page that will make all the links on my page have target="_blank"?
I want to have a checkbox that says something like "Open all links in new page/tab" on my site that when checked will change the target and unchecked will put it back to how it was.
jQuery example
$(function() {
$('#yourCheckoxId').toggle(function() {
$('a').attr('target', '_blank');
},
function() {
$('a').removeAttr('target');
});
});
You might want to try jQuery as an alternative to genuine Javascript
the actual code could look something like that:
$('a').attr(target, '_blank')
Modifying the target attribute of all the anchors on the page is merely a matter of getting all links, and setting their target properties one by one:
var anchors = document.getElementsByTagName("a");
for(var i = 0; i < anchors.length; i++) {
anchors[i].target = '_blank';
}

Categories