I'm trying to route to a dynamic page in JavaScript,
Is there any way I can do this,
localhost/page.html/001
Can I write a code like,
If (url last characters == 001) {
//Do something
}
<script type="text/javascript">
var lastUrl = window.location;
lastUrl = lastUrl.replace("localhost/page.html/", "");
if(lastUrl == "001"){
alert(lastUrl);
}
</script>
You could use:
const currentUrl = window.location.href
To get the current URL of the side (In this case localhost/page.html/001), then:
const filterUrl = currentURL.split("/");
if (filterUrl[2] === '001') { /* Do stuff */ } else { /* Do other stuff */ }
If your URL's are going to be always like that you could use this little snippet to filter them.
Related
I want to toggle between two jQuery functions. It has to be done on page load - and each page load should only execute one of the scripts.
This is what I got so far:
HTML:
<button class=".click">Click me</button>
Script:
$(function() {
if (window.location.href.indexOf("addClass") > -1) {
$("body").addClass("test");
}
else {
$("body").addClass("secondtest");
}
$('.click').on('click', function() {
console.log("Clicked");
var url = window.location.href;
if (url.indexOf('?') > -1) {
url += '?param=addClass'
} else {
url += '?param=1'
}
window.location.href = url;
});
});
This Gets me a bit on the way, the first click adds ?param=1 on the first click - nothing happens - second click it adds the ?param=addClass and the body gets the class. If I click again it adds ?param=addClass every time.
I want one of the script to run as default - then I want the first button click to reload and run the other script instead. If I click once more I want it to reverse the url so the first script loads, like a toggle.
I now there is an easy way to just toggle classes, but I specifically need to run one of two scripts on a new page load.
Update:
$(function() {
if (window.location.href.indexOf("addClass") > -1) {
$("body").addClass("test");
}
else {
$("body").addClass("secondtest");
}
$('.click').on('click', function() {
console.log("Clicked");
var url = window.location.pathname;
var url = window.location.href;
if (url.indexOf('?param=1') > -1) {
url = url.replace("param=1", "")+'param=addClass'
} else {
url = url.replace("?param=addClass", "")+'?param=1'
}
window.location.href = url;
});
});
This set the body class on first page load - then first click ads ?param=1 but doesnt change the body class. Second click replaces ?param=1 with ?param=addClass and changes the body class - after that the toggles works. So How do I make it work from the first click?
This will be the default functionality, if no query string is present then add ?param=1:
var url = window.location.href;
if(url.indexOf('?param=1')==-1 )
{
window.location.href = url+"?param=1";
}
This will be the onclick functionality to toggle the urls as it is replacing the existing functionality.
$('.click').on('click', function() {
var url = window.location.href;
if (url.indexOf('?param=1') > -1) {
url = url.replace("param=1", "")+'param=addClass'
} else {
url = url.replace("?param=addClass", "")+'?param=1'
}
window.location.href = url;
});
If you want to toggle the classes as well you can use .toggleClass("test secondtest")
The issue you have is in this if:
var url = window.location.href;
if (url.indexOf('?') > -1) {
url += '?param=addClass'
} else {
url += '?param=1'
}
Scenario 1: /test.html
indexOf('?') will be negative. You will then redirect the user to /test.html?param=1
Scenario 2: /test.html?param=1
indexOf('?') will then be positive. You will then redirect the user to /test.html?param=1?param=addClass
Scenario 3: /test.html?param=addClass
indexOf('?') will then be positive. You will then redirect the user to /test.html?param=addClass?param=addClass
So... what is wrong?
You are using window.location.href. Excellent for setting the path but bad if you want to actually manage the query parameters.
Solution
var url = window.location.pathname;
var hasParams = window.location.href.indexOf('?') > -1;
if (hasParams) {
url += '?param=addClass'
} else {
url += '?param=1'
}
window.location.href = url;
Since you are redirecting on the same host (seen with your code), you only need the pathname. pathname doesn't include parameters (?key=value&...) and can be used to redirect a user on the same domain.
Sometimes because of cache I add # in my url, like this:
http://www.example.com/#lang=3201954253
What I need is to check if there is #lang in url and remove it if present.
you can clear the hash.
window.location.hash = '';
or you can even use history api History Api. history.pushState and replaceState
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one.
window.history.replaceState( {} , 'foo', '/foo' );
You may try like this:
if(window.location.hash) {
// code
} else {
// code
}
or you may try this:
<script type="text/javascript">
if (location.href.indexOf("#") != -1) {
//code
}
</script>
If you want to remove it then you may try this:
window.location.hash = ''
On a side note:
You may try
window.location.href.split('#')[0]
to remove anything after # without refreshing your page.
if (window.location.hash.indexOf("lang")) {
window.location.hash = "";
}
var tel = window.location.href;
if(tel.indexOf("#") > -1){
alert("found");
} else {
alert('not found')
}
I have java script function to check the URL and split it,
I ask a question and depends on the answer it will forward the user page
all works fine until I use window.location.assign();
with string inside (=window.location.assign(path);) instead of fixed URL (=window.location.assign("http://stackoverflow.com");)
what can i do?
thanks...
var register=...;
var login=...;
function link(type) {
var urlPath = document.URL.split("/");
if (type == "register") {
var path= urlPath[2] + register;
window.location.assign(path);
}
else {
var path = urlPath[2] + login;
window.location.assign(path);
}
event.preventDefault();
}
You should use the full URL.
window.location.assign(urlPath[0]+'/'+urlPath[1]+'/'+urlPath[2]+register);
window.location.assign(urlPath[0]+'/'+urlPath[1]+'/'+urlPath[2]+path);
Or
window.location.assign(window.location.origin+register);
window.location.assign(window.location.origin+path);
So, I have two select boxes on a webpage, but in different anchors (one on the page, the other in an iframe) and I'm trying to get the code to detect which anchor it's in, and then relay the selected value in that box to a link. Here's my code:
function locationHashChanged() {
if (location.hash === "#player") {
function setText(text) {
var selectVal = text;
var url = $('twitter').attr("href");
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#twitter').attr("href", url);
}
}
if (location.hash === "#embeds") {
$(function () {
var $twitter = $('twitter');
$('#iframe').on('load', function () {
$(this).contents().find('#cds').change(function () {
var selectVal = $(this).val() || 'nothing much';
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#twitter').attr("href", url);
}).change();
});
});
}
}
I know this is probably not right, or anywhere near right, but am I on the right track? I'm honestly a complete noob when it comes to javascript. Thanks in advance
Apart from what exactly your function looks like, it's not executed on hash change right now.
You use jQuery, so you can listen for hash change like this:
$(window).on('hashchange', function() {
// your locationHashChanged() function goes here
});
With this, every time the hash changes your function will be executed. The very base of your code is alright:
if (location.hash === "#player") {
// this is executed if hash changed to #player
}
if (location.hash === "#embeds") {
// this is executed if hash changed to #embeds
}
Although, inside your if blocks you declare functions (which doesn't make much sense here).
Also note that if the iframe is not from your domain, you won't be able to get any data from it. If that's the case, read more about same origin policy.
How do I check if the current URL ends in: #!/about or #!/ask using JavaScript?
window.location.hash contains the current hash code, so basically:
if(window.location.hash === '#!/about') {
// Do something
} else if(window.location.hash === '#!/ask') {
// Do something else
}
You can use it however you need to.
Edit: As zzzzBov points out, if you need some jQuery, put it in a $(document).ready handler. ;)
To fetch the current url using jQuery
$(location).attr('href');
Here's the code snippet
jQuery(document).ready(function() {
var url=$(location).attr('href');
var match1 = arr.match('#!/about');
var match2 = arr.match('#!/ask');
if(match1){
alert("match1 found");
} else if{
alert("match2 found");
}
});