How to get current url in jquery - javascript

I can't explain myself in title. What i want is get string between slashes. Like that:
www.example.com/foo/bar/id/1
i want to get "foo". Because i made these codes.
select: function(event, ui) {
if(window.location.href = "news/" + ui.item.slug){
window.location.href =null;
}
else
window.location.href ="news/" + ui.item.slug;
}
I have a autocomplete search field. When i clicked a result, its redirecting me to www.example.com/news/34523
In this page if i use search field again, it redirects me to www.example.com/news/news/12412 After that i got 404. But if i am not in news tab, for example www.example.com/foo its working perfecly when i use search field. I just need an if statement, if i am in news pages act like another page.

You could simply use the location.pathname property to get the part between the first and second slash and run code based on this.
console.log(window.location.pathname);
console.log(window.location.pathname.split("/")[1] === "foo");
To show that this works, here is another snippet, acting as if url was window.location:
let url = document.createElement('a');
url.href = "http://www.example.com/foo/bar/id/1";
console.log(url.pathname);
console.log(url.pathname.split("/")[1] === "foo");

The problem seems to be with your url that gets redirected. Try the below code.
select: function(event, ui) {
if(window.location.href = "/news/" + ui.item.slug){
}
else
window.location.href ="/news/" + ui.item.slug;
}

Related

How to pass incoming Google Analytics campaign utm strings to outgoing clicks

I want to have a setup where if I bring traffic to my site by using Google Analytics campaign strings: utm_campaign and utm_source, those strings would be stored and then appended to any outgoing link/click from my site.
Example if I want to bring traffic from a news article in Linkedin
Incoming link:
https://mywebsite.com/landing-page/?utm_campaign=news&utm_source=linkedin
I want it so when a visitor clicks on the outgoing links (or any link in my website), the outgoing link will have the utm string appended like:
https://outgoinglink.com/welcome-aboard/?utm_campaign=news&utm_source=linkedin
Can anyone help how to have something like this.
My website is in Wordpress and there seems no specific plugin for this.
You can do this in Javascript and definitely it would be easier with jQuery, so I will give you jQuery solution.
$(function(){
var params = window.location.search;
if (!!params) {
$('a[href]').each(function(){
$(this).attr('href', $(this).attr('href') + params);
});
}
});
Put this in your header and it will add parameters to your links. Note that this will potentially break your links if they already have query strings attached. In that case this code should have 1 more edge case.
$(function(){
var params = window.location.search;
if (!!params) {
$('a[href]').each(function(){
if ($(this).attr('href').indexOf('?') === -1) {
$(this).attr('href', $(this).attr('href') + params);
} else {
$(this).attr('href', $(this).attr('href') + '&' + params.substr(1));
}
});
}
});
Note that this code is for you to learn, it can be optimised and made more secure for production purposes.
If you need to persist parameters on 2nd or later page, you should first add it to localStorage and then read it from it and append on every link again.
Hope that helps
EDIT:
You can check this pen,
https://codepen.io/mnikolaus/pen/dZeVLv
EDIT 2:
jQuery(function(){
var params = window.location.search;
if (!!params) {
jQuery('a[href]').each(function(){
if (jQuery(this).attr('href').indexOf('?') === -1) {
jQuery(this).attr('href', jQuery(this).attr('href') + params);
} else {
jQuery(this).attr('href', jQuery(this).attr('href') + '&' + params.substr(1));
}
});
}
});
Try this. A client of mind wanted to do the same thing few month ago, I give him this her this and it's working now.
<script type="text/javascript">
(function ($) {
// Get the utm tag from current url
var params = window.location.search;
// if utm available...
if (!!params) {
$('a[href]').each(function(){
// Apply the extracted utms to link
$(this).attr('href', $(this).attr('href') + params);
});
}
}(jQuery));
</script>
It is basically checking for any url without utm tags.
Hope it helps.

if confirm ignores location.href

The following code reloads the page rather than the desired URL
function delFile(name,id) {
if (confirm('Are you sure you want to DELETE '+name+'?')) {
location.href='/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id ;
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id);
}
else {
return false;
}
}
In the alert, the id is shown as being added properly and the URL is correct. I can copy it from the alert, then use that text to get the right result. Other scripts on the same page that use similar location.href are working perfectly but this is the only one using confirm.
I've also tried
window.location.href = "http://stackoverflow.com";
But the page still reloads.
The triggering link is:
onClick="return delFile('Bill','1234')
The href on the triggering link is still being linked to, because delFile() only returns false if the confirm is not accepted -- that's what's causing the page reload. When the function returns true, the link fires before the redirect occurs.
You want the function to return false in all cases, so don't put the return in an else clause.
function delFile(name, id) {
if (confirm('Are you sure you want to DELETE ' + name + '?')) {
location.href = '/cgi-bin/cnc.cgi?phrsrg~038919718485478~' + id;
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~' + id);
}
return false; // always, since you always want to prevent the link's default behavior. (Could also use event.preventDefault here.)
}
test
function delFile(name,id){
if (confirm('Are you sure you want to DELETE '+name+'?')) {
/* var fullpath = better to use the full url name/link;*/
var url = '/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id;
window.open(url, '_parent');
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id);
}
else {
return false;
}
}
It looks like the delFile() function is missing the opening curly brace, so I would start by fixing that. If the issue persists, check the JS console. Also, posting a codepen would be helpful.

Show content on certain URL

I am using an online store solution which allows me set up a simple online shop. I cannot use any code other than html/css/javascript.
I have put in a simple image-slider in the template. But i want this slider to only be shown on the frontpage. Now its shown on every-page.
Can i use a javascript functions that says something like this: "if url is "www.example.com" then show image-slider else hide it."
Something like this maybe?
<script>
$(function() {
if(document.URL == "http://example.com/") {
...
...
</script>
Thanks on beforehand :)
I don't know the exact circumstances of what you're trying to do it or why you'd need it, but
if (location.href == "http://example.com")
Should do it. Location.href returns the URL of the page, like "document.URL" in your example.
If you're looking to just get certain parts of the URL, this is a really cool tip I found here.
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.hostname; // => "example.com"
parser.pathname; // => "/pathname/"
Essentially what this does is creates a link element in your JavaScript that has properties that return different parts of the URL. This would be relevant if there could be multiple URLs for your index page. For instance, if the user is currently at http://example.com/index#something.
(location.href == "http://example.com/")
Would return false. However, if you did this in your code,
var parser = document.createElement('a');
parser.href = "http://example.com/index#something";
(parser.hostname+parser.pathname == "example.com/index")
That last line would return true for both http://example.com/index and http://example.com/index#something.
Taking the information you've given about the website, here's my best guess as to what your code should look like.
var parser = document.createElement('a');
parser.href = location.href;
if (parser.hostname+parser.pathname != "example.com/index") //If user isn't on the index page
{
$(".slidewrap").hide(); //Hide the div with the class slidewrap
}
window.location is the right area, it exposes a hostname property so you can check just the site name rather than the whole URL, and pathname for just the local path within the site. See https://developer.mozilla.org/en-US/docs/Web/API/Location
So if the home page is http://www.example.com/, then window.locaton.pathname === '/'
i.e.
<script>
$(function() {
if (location.pathname == "/") {
...
}
});
</script>
Im just adding the solution as an answer as i got it to work by mixing j4g and duncans codes:
<script>
$(function() {
if(location.pathname !== "/") {
$("#slidewrap").hide();
}
});
</script>
As i understand it. It says: If location is not index then hide #slidewrap :D And that works perfectly. Thanks.

Ajax success if inArray breaks a href appending

I just thought I was very clever. Turns out I was wrong.
My ajax login works fine. I'm using it to append the username to a link which also works brilliantly.
Within a subset of pages I'd like it to refresh the page. This also works brilliantly.
However, the refresh stops the href being appending. I checked it and I can see the username?="username here" is working and it's immediately changed to username?=
I figure the reload would only happen in the cases when the if statement is true.?
if(data.success == true){
var thisPage = window.location.pathname;
var refreshArray = new Array("training_chap01.php","training_chap02.php")
if(jQuery.inArray(thisPage,refreshArray)){
location.reload();
}
$('#loggedIn').show();
$('a[href="userProfile.php?username="]').each(function(){
this.href += username;
});
$('#loginContent').slideToggle();
$('#loggedOut').hide();
Thanks for any help.
inArray returns an index, not a boolean value, try this:
if(jQuery.inArray(thisPage,refreshArray) > -1)
Documentation: http://api.jquery.com/jQuery.inArray/

window.location.hash keeps appending name instead of replacing it when links are clicked

Ok, I have this script working 99% of how it should be working, but I can't seem to figure out this little bit.
When the user clicks on a link it takes the href value and chops it up and gives me the last segment of the url. In this example I'll say its home
so my script then grabs home and adds it to the url in the address bar.
so it look like http://www.site.com/user/s2xi/home after its done doing its magic.
But originally I had an issue where because of the nature of how links work I suppose it would keep appending my url like this http://www.site.com/user/s2xi#/home which on my server doesn't exists
So I was able to get rid of the # and it got everything back to normal...oh wait, no not everything always works perfect on the first try...
so i then realized that my script was appending link names instead of replacing them... oh noes, now what?
my links would now look like this: http://www.site.com/user/s2xi/home/someOtherLink
it would append the new link name to old link name instead of replacing it...
my script:
var newHash = "",
shref = "",
content = '#content',
$c = $("#content"),
$cw = $("#content-wrapper");
$(".menu-link, #my-account-link").live('click', function(){
shref = $(this).attr("href").split("/");
parent.location.hash = $(this).attr("href");
window.location.hash = shref[5];
console.log(window.location.hash);
return false;
});
$(window).bind('hashchange', function(){
if (location.href.indexOf("#") > -1) {
location.assign(location.href.replace(/\/?#/, "/"));
}
newHash = window.location.hash;
//newHash = window.location.hash.substring(1);
//newHash = window.location.substring(1);
//console.log(newHash);
if(newHash)
{
$cw.find(content).fadeOut(200, function() {
$cw.load(newHash + " #content-wrapper", function() {
$c.fadeIn();
});
});
}
});
$(window).trigger('hashchange');
what could be wrong with the script logic?
First, without /.../g, you're just replacing the first match, which may be what you want.
You logic seesm to be:
Replace # with link, so the hash now becomes a link
When you click on a link, the handler takes the last segment in the current href attribute and put it into a hash. Notice that you have not removed that segment from the url.
In other words, say it starts with:
http://www.site.com/user/s2xi
You href, say, is http://www.site.com/user/s2xi/home. Then on your click, you get shref[5] = "home". And you add it to hash of the current url, which makes it:
http://www.site.com/user/s2xi#home
And then you convert that hash back into a link:
http://www.site.com/user/s2xi/home
All is fine. The second time you click on a link, say, http://www.site.com/user/s2xi/foo. On your click, shref[5] = "foo".
You then add it to your hash of the current url:
http://www.site.com/user/s2xi/home#foo
Then you convert that hash back into a link:
http://www.site.com/user/s2xi/home/foo
Voila. You appened the link instead of replacing it. You should be replacing the segment in the url.

Categories

Resources