Detect a URL and change it - Javascript? - javascript

I have a wordpress website which contains over 900 posts. I am affiliate with a number of companies however they have since changed the URL.
How can I detect a URL say www.abc.com.au and change it to www.xyz.com.au when they are <a target="_blank">?

Use Jquery:
('a').each(function( ) {
if($(this).attr("target") == "_blank" && $(this).attr("href") == "www.abc.com.au")
$(this).attr("href", "www.xyz.com.au");
});
I did not test my code.
You can also use modrewrite and .htaccess.

If you need to edit the links in your own posts it might be worth it to see if there is a wordpress bulk-update plugin that suites your needs, but in JavaScript on the page you can do something like
$('a[target="_blank"]').each(function() {
var href = $(this).attr('href');
if (href.indexOf('www.abc.com.au') > -1) {
$(this).attr('href', href.replace('www.abc.com.au', 'www.xyz.com.au'));
}
});
which finds all a tags with target _blank and then updates the href if it contains the original domain by replacing that string with the new one.

Related

Add "#" hash correctly to url with jquery

I am a bit confused, because I just want to add a hash to an existing url via varibale and open it via a href.
Example:
$( ".MyLink" ).each( function(){
var href = $(this).attr('href');
$(this).attr("href", "https://website.com/subpage#" + href);
});
Result (browser url) after clicking on this link:
https://website.com/subpage/#test
If I am right, a correct hash link should look like this ...
https://website.com/subpage#test
... without the "/" after subpage.
So, I am correct or it doesn't matter? If yes, how can I change it?
I also realized that my browser(s) change my url from https://website.com/subpage#test to https://website.com/subpage/#test if I just add it in the browser bar and press enter. Is that new?
Maybe it is important to know that I use wordpress?
OK, it seemes to be a php/browser/wordpress rule that # become /#, because this script creates an endless refresh-loop for me:
var urlupdate = window.location.href.replace("/#", "#");
window.location.href = urlupdate;
Update: As described in this answer, it shouldn't make a difference if your Javascript was written properly, it seems to be even considered as a best practice. If you want to get rid of it anyways you may want to check your wordpress settings, maybe the second answer of the given question may give you a hint!
In case that the trailing slash comes from the a tag, you could check whether the string in the href attribute starts with a slash and remove it then:
$( ".MyLink" ).each( function(){
var href = $(this).attr('href');
if (href.charAt(0) === '/') {
href = href.substring(1, href.length);
}
$(this).attr("href", "https://website.com/subpage#" + href);
});

Inject GET parameter to target URL of a button, on click

I have multiple buttons with the class myButton. Each button has a value which is send to a server on click. The target URL of the button does look like this:
http://mysite/test/test.html?cid=15
After I click on the button, the following GET parameter should be added to the URL and then the button should be submitted:
mySessionVar=1
So the new URL should look like this:
http://mysite/test/test.html?cHash=d009eb3f9f4e1020435b96a8f7251ad5&mySessionVar=1
Why I have to inject it?
I am working with fluid. AFAIK it is not possible to manipulate fluid tags with JavaScript. However, I need to add a sessionStorage item value to the fluid tags arguments attribute.
My fluid code:
<f:link.action controller="Download" action="download" arguments="{cid: category.uid}" class="myButton">Download</f:link.action>
So my attempt is to append my sessionStorage item as GET parameter to the target URL of the button and then send it, e.g.:
$(".myButton").on
(
"click",
function(event)
{
//First prevent the default event
event.preventDefault();
...inject the sessionStorage item as GET parameter to the target URL of the button, then do whatever the button would do normally...
//Go to new URL
window.location.replace(NEW URL);
}
);
Is this possible?
EDIT: This is how the rendered HTML of the buttons looks like:
<a class="myButton" href="/de/mysite/test/test.html?tx_mydownloads_myfilelist%5Bcid%5D=15&&tx_mydownloads_myfilelist%5Baction%5D=download&tx_mydownloads_myfilelist%5Bcontroller%5D=Download&cHash=d009eb3f9f4e1020435b96a8f7150ad5">Download</a>
EDIT: I have another idea, maybe I could just read the target URL somehow, then add my new GET param to it and then load that URL with window.location.replace?
You can indeed just use the href from the button and use it to feed window.location.href, like so:
$('.myButton').on('click', function(e) {
e.preventDefault();
var href = $(this).attr('href'),
queryString = 'mySessionVar='+sessionStorage.getItem("myItem"),
newHref;
if (href.indexOf('?') !== -1) {
newHref = href + '&' + queryString;
} else {
newHref = href + '?' + queryString;
}
window.location.href = newHref;
});
This also handles the case when there is no previous query string present on the link and appends it with ? instead of &, but that part can be omitted if that won't happen in your app.
The following snippet should be enough to add your mySessionVar=1 parameter to the href attribute:
$('.myButton').on('click', function(e) {
$(this).attr('href', $(this).attr('href') + "&mySessionVar="+ sessionStorage.getItem('myVar');
});
You don't have to prevent the default, because your click handler function is called before the default event handler (who does roughly speaking: read the href attribute and load it).
You can use .serialize function in jquery which is simple and modern function to get all the selected buttons/filters into a url param format with amberson simple. I can't explain more clear than what is said in Jquery website. Please refer the link below to find how to use the function. https://api.jquery.com/serialize/#serialize

How to scroll to a specifc element when there is already an # anchor on the url

I have a web site on based on SkelJS that currently loads a different part of the webpage by appending an #anchor to the url like this:
Note that #blog loads the blog page, the scroll is at the top. Inside the Blog page I need to scroll to a certain article. How can I use two anchors so that something like #blog#article_x would work? I suppose I have to look for a workaround since anchoring 2 ids makes no sense, is there a work around?
Additional notes:
Note that if a change #blog to #article_x it actually goes to the desired article however if someone shares the link it won't go to the article because it will look for #article_x on the homepage, where it does not exists.
Here is a demo of the template I'm using (http://html5up.net/uploads/demos/astral/#) note how the #anchor loads the desired page.
You can use a hash that contains both page and element. Then split and then do your page load then scroll, i.e. #blog,someelement
//on page load or wherever you detect the hash
$(function(){
var hash = window.location.hash;
var ele = null;
//Detect if there is a splitable hash
if(hash.indexOf(",") != -1){
var parts = hash.split(",");
hash = parts[0];
ele = jQuery("#"+parts[1]);
}
//whatever function you do to load the blog page
loadPage(hash,ele);
});
function loadPage(page,ele){
//do page loading
$("#page").load("http://someurl.com",function(){
//if there was no second part to the hash
//this will be skipped
if(ele){
$("html,body").animate({
scrollTop: ele.offset().top
},1000);
}
});
}
JSfiddle Demo
Considering the ID of the element that you want to scroll to is myelement you can use below jquery code to smoothly scroll to it.
$("html,body").animate({scrollTop : $("#myelement").offset().top},1000);
We can scroll to specific div when it has id or class
var $id=window.location.href.split('#')[1];
$('html, body').scrollTop($("#"+$id).offset().top)

change url to reflect content on the page hidden / displayed with Javascript

I am currently making a website for an architecture firm, HLArchitects. In the projects page I have created an HTML / Javascript image gallery. slightly above the main big image to the right an option can be found to choose between images / information. I use Jquery to show and hide the information or the images, however i don't feel this is such a great way to do so. It can be viewed here for reference: http://www.hla.co.za/projects/Hyuandai_Training_Centre/
Here is the relevant Javascript:
$(".selector a").click(function(){
if ($(this).attr("data-show") == "images") {
$("#info").fadeOut("fast");
$("#displayImg").fadeIn("fast");
$("#imageFlow").fadeIn("fast");
} else if ($(this).attr("data-show") == "info") {
$("#displayImg").fadeOut("fast");
$("#imageFlow").fadeOut("fast");
$("#info").fadeIn("fast");
}
})
Relevant HTML:
<p class="selector">images | information</p>
My problem is that the url does not change to reflect the content, but I do not want to make a separate page. I could imagine i would need to make use of link anchor's but am not to sure how to do so.
Thank you in advance
You can change the hash of an url by using:
window.location.hash = 'images';
EDIT:
Firstly, in this context you don't need to include the hash symbol!
Secondly, I missed the obvious, you only need to change the HTML to this to update the URL correctly:
<p class="selector">
images
information
</p>
Then you can use the following in your jQuery, note I've included the attribute check inside the selector itself:
$(".selector a[href=#images]").click(function() {
$("#info").fadeOut("fast");
$("#displayImg").fadeIn("fast");
$("#imageFlow").fadeIn("fast");
});
$(".selector a[href=#info]").click(function() {
$("#displayImg").fadeOut("fast");
$("#imageFlow").fadeOut("fast");
$("#info").fadeIn("fast");
});
If you want to refresh the page and get the same content, you can check the hash tag by doing the following (you may need to edit this depending what elements are showing initially):
$(document).ready(function() {
if (window.location.hash == '#images') {
$("#info").hide();
$("#displayImg").show()
$("#imageFlow").show();
}
else if (window.location.hash == '#info') {
$("#displayImg").hide();
$("#imageFlow").hide();
$("#info").show();
}
});
If all you're doing is setting text in the URL, you can do this easily by setting location.hash
location.hash="#SomeTextHereThatMayOrMayNotNecessarilyBeAnAnchor"
^ Note that "#" is important

Need a quick jquery solution to capture the current url and inject it into another url link

My brain is fried ATM and I have a looming deadline, I am looking for a way to grab the currently viewed pages url and place it into another link for bookmarking/social links.
Facebook link:http://www.facebook.com/share.php?u=[PAGEURL]
Myspace link:http://www.myspace.com/Modules/PostTo/Pages/?u=[PAGEURL]
Twitter link: http://twitter.com/home?status=Check+this+out:+[PAGEURL]
Stumble Upon link:http://www.stumbleupon.com/submit?url=[PAGEURL]
Digg link: http://digg.com/submit?phase=2&url=[PAGEURL]
I need to replace [PAGEURL] with the URL for the page being viewed. Any help is most appreciate. i have been looking for a while now and can't seems to find an answer that fits this specific circumstance.
It'd help to see what kind of structure those links are in. But, here's some jQuery that might point you in a good direction. It assumes your social bookmarking links are in a container with id="socials", but you can mash the selector to do whatever it takes to get hold of your social links.
$(function() {
var links = $('#socials a'),
matchExp = /\[PAGEURL\]/,
currentURL = location.href;
links.each(function() {
var currentHREF = $(this).attr('href');
if (currentHREF.match(matchExp)) {
$(this).attr('href',currentHREF.replace(matchExp,currentURL));
}
});
});
This uses the attr function to get where the link points to, then a regular expression (eww!) to check if the link has [PAGEURL] in it, and to replace [PAGEURL] with location.href, which is the url of the current page. Here's a handy regexp tester.
window.location.href should work.
I imagine it would be something like
var faceBookUrl = "http://www.facebook.com/share.php?u=" + location.href

Categories

Resources