I've read the other questions about this same topic, and I feel like I understand what to do, but it's not working.
I have two domains, out of necessity. On one specific page, I'm trying to update the links so that they point to the second domain. It functions if I just loop through every 'a' element, but not if I try to match specific links. I left my first attempt commented out, I'm not sure which method is better.
This function gets called if one is on that particular page, but are from a different country. I can't see what I'm doing wrong.
I thought that this.href should get the full, qualified URL but it doesn't seem to be doing so.
function updateLinksToUSAstore() {
$('a[href*="manitobahdev.myshopify.com"]').each(function() {
// $(this).attr('href', $(this).attr('href').replace('manitobahdev.myshopify.com', 'manitobahdev-us.myshopify.com'));
this.href = this.href.replace('manitobahdev', 'manitobahdev-us');
});
var CountryName = localStorage.getItem('CountryName');
// Change currently selected country text
$('#country-label, #country-label-mobile').text(CountryName);
}
Try it like this:
var href = null;
$("a").each(function()
{
href = $(this).attr("href");
if(href.contains("manitobahdev.myshopify.com"))
{
$(this).attr("href", href.replace("manitobahdev.myshopify.com", "manitobahdev-us.myshopify.com"));
}
});
I'm on mobile right now, so i was not able to test this. Sorry if it doesn't work.
Plus, i don't really understand why you'd want to edit only the manitobahdev part to manitobahdev-us, since both end with myshopify.com
May be it will help you.
//get all selector
var celem=jQuery('a[href*="manitobahdev.myshopify.com"]');
for(var i=0;i<celem.length;i++){
console.log('====== BEFORE ====');
//get each href of selector
var ele=jQuery(celem[i]).prop('href');
console.log(ele);
jQuery(celem[i]).prop('href',ele.replace('manitobahdev','manitobahdev-us'));
console.log('====== AFTER ===');
ele=jQuery(celem[i]).prop('href');
console.log(ele);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id='test1' href="manitobahdev.myshopify.com/ABC">Test 1</a>
<a id='test2' href="http://manitobahdev.myshopify.com/ZAXC">Test 2</a>
<a id='test3' href="manitobahdev.myshopify.com/USER/1">Test 3</a>
Related
I have a <ul><li><a> structure that is stylized very specifically and has 9 elements separated in 3 columns. I want to add another item without making a 4th column so the solution I'm considering is having 2 links in one 'slot'.
The problem with this is that the <ul><li><a> is structured such that adding an <a> will automatically create another slot (vertically).
I'm hoping not to have to recreate the entire structure from scratch in order to accommodate this change, so I'm trying to come up with a hack.
I KNOW THIS IS UGLY AND WEIRD but it does make for an interesting problem atleast...
I tried doing:
link1 <span onclick="location.href ='link2.html'">link2</span>
But that doesn't work - I also tried with jQuery but that didn't work either. Is there a workaround/hack here or do I have to restructure the entire list?
Here's a quick and easy way to have the a and span elements take you to different links. (I commented out the actual link and used alerts instead, since the links won't load in the frame anyway.)
function goToLink(e, that) {
e.stopPropagation();
if (that.tagName.toUpperCase() == "A") {
// if anchor was clicked
alert("1st link");
//window.location.href = "http://www.google.com";
}
else {
// if span was clicked
alert("2nd link");
//window.location.href = "http://www.yahoo.com";
}
}
link1 <span onclick="goToLink(event, this);">link2</span>
The stopPropagation() call prevents the first link from loading when the second link is clicked.
$('#link2').click(function() {
window.setTimeout(function() {
location.href = $('#link2').attr('data-href')
}, 10)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
link1 <span id='link2' data-href="link2.html">link2</span>
I am looking to change part of many links on a webpage. I want to change any link that has "oldTag" to "newTag".
Ex.
www.google.com/WillBeDifferent/oldTag
to
www.google.com/WillBeDifferent/newTag
Basically any link where oldTag shows up I want to replace it with newTag. I am new to this but I have been researching for a few days and nothing I can come up with seems to work.
The context is I have Google Tag Manager checking to see if a cookie is present and if it is then it will trigger a tag to change all of the links to the newTag.
Not sure if I should or can use jQuery or Regex...
Here is what I have played with from scouring the internet.
var anchors = document.querySelectorAll('a[href*="oldTerm"]');
Array.prototype.forEach.call(anchors, function (element, index) {
element.href ="newTerm"; });
It replaced all of the links with the oldTerm but replaced them with http://www.google.com/newTerm.
$("a[href^='oldTerm']")
.each(function() {
this.href = this.href.replace(/oldTerm/g,
"newTerm");
});
Could not get this to work but found it somewhere else on here.
Not sure where to look now... any help would be great.
you are very close but need to use * instead of ^
$("a[href*='oldTerm']")
.each(function() {
this.href = this.href.replace(/oldTerm/g, "newTerm");
});
As mentioned in the title is the question what does this all affect.
The code works fine and you want really see anything happen expect of the "href" attribute from the <a> tag gets changed to "iref".
I do this to load the content later via jquery.load()
Should I do this different? What would be the "right" way to do it?
What about google, does it affect google robots? I ask this because: if there is no javascript turned on, the links want change from href to iref and work off course. So the robots can follow them or not?
Thanks for all the answers.
There is a fiddle
<a class="top-nav animMainBox" href="/home.html">Home</a>
<a class="top-nav animMainBox" href="notathome.html">Not at home</a>
<a class="top-nav animMainBox" href="/contact.html">Contact</a>
<style type="text/css">
a{margin:10px;}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
hrefToIref();
$(document).on('click','.animMainBox',function(){
loadNewBox($(this), true);
});
});
function hrefToIref() {
$('.animMainBox').each(function(){
var url = $(this).attr('href');
$(this).attr('href','javascript:;').attr('iref',url);
});
$('.button').each(function(){
var url = $(this).attr('href');
$(this).attr('href','javascript:;').attr('iref',url);
});
}
function loadNewBox($this,animate) {
// loading and returning new boxes via
// var url = $this.attr('iref');
// $(".wrapper").load(url+' .toggle.box',{noncache: new Date().getTime()}, function(response, status, xhr) {}
}
</script>
Should I do this different?
Yes, definitely. iref attributes look quite invalid.
Can robots follow them or not?
Yes, they usually will only look at your static HTML markup with the href attributes.
What about google, does it affect google robots?
Google is a bit different I think as they can view pages with JS turned on. I don't know whether your script will stop them from following the links.
What would be the "right" way to do it?
Just leave the href attributes as they are. Prevent following them when they're clicked.
$(document).on('click','.animMainBox, .button', function(e){
e.preventDefault();
loadNewBox($(this), true);
});
function loadNewBox($this,animate) {
var url = $this.attr('href');
// ^ just use the correct attribute
…
}
Why not just like this :
$(document).ready(function(){
$('a').click(function(){ return false; });
$(document).on('click','.animMainBox',function(){
loadNewBox($(this), true);
});
});
This will stop the links from working and you can load something later on.
Search robots can still visit the links yes.
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;
}
}
})
I want to change the param of link dynamically.
For e.g.
Link1
Link2
Link3
by default their url is ?item=text i.e. for link1(href="?item=link1") etc..
but when i click link1 the url of link2 and link3 should be
link2(?item=link2&item=link1)
link3(?item=link3&item=link1)
any idea how to acheive this?
Thanks,
Assuming all the links have a class of superspeciallink, this should work:
$('a.superspeciallink').bind('click', function(){
var querystring = this.search; // The search property of links gives you the querystring section of their href
var originalhref = this.href;
$('a.superspeciallink').each(function(){
if(this.href != originalhref) {
this.href = this.href + '&' + querystring.slice(1);
}
});
return false;
});
This would mean that these links never get followed though — I assume some other JavaScript would be reading out these query string values eventually.
Invoke jQuery something like the following:
$("my#links").attr("href", "new/href/value");
You'll need to write a function to calculate the new value of href for each link, of course.