So I have this piece of code where the form is hidden until I click on the element. If I'm in that page (profile.php) it shows the form and scrolls down to it but if I'm not on that page (e.g: index.php) it goes to thatpage(profile.php) but doesn't show the form and doesn't scroll down to it until I click again on that element (which it is in the menu)
So here is my html code:
<a id='showForm'>Apply</a>
<div class="formL" style="display:none">
//code
</div>
and here's my script:
<script>
$('#showForm').click(function() {
let currentURL = $(location).attr("href");
let redirectURL = "http://127.0.0.1/dealaim/profile.php#formL"
if (currentURL !== redirectURL) {
$(location).attr("href", redirectURL);
var formL = $('.formL').show();
document.documentElement.scrollTop = formL[0].offsetTop;
} else {
var formL = $('.formL').show();
document.documentElement.scrollTop = formL[0].offsetTop;
}
</script>
The code after your redirect won't do anything; that code needs to run on the page you redirect to, not the page doing the redirect.
Once the redirect takes place, it's a question of passing along some info that the page can receive and use to automatically invoke the function. So:
$('#showForm').click(function() {
let currentURL = location.href;
let redirectURL = "http://127.0.0.1/dealaim/profile.php?showForm=1"
if (currentURL !== redirectURL)
location = redirectURL;
else {
let formL = $('.formL').show();
document.documentElement.scrollTop = formL[0].offsetTop;
}
});
if (location.href.includes('showForm=1') $('#showForm').click();
Note also there's no point at all in doing $(location).attr('href') - you just unnecessarily invoke jQuery and wrap what is a simple object-and-property combo in its API. Just use location.href.
I have a sample page, let' say testpage.pl When I choose English version, GET parameter is added to URL, like /?language=en.
Afterwards, when I click menu positions, they are in the English version so everything is OK.
But if I want to have English version of a subpage directlty after pasting URL in a browser, like
http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html)
the Polish version is opened. So I've made a simple redirect function like below, but it comes to the loop after first start. This function redirect to the same page, but before it tries to redirect to this first URL with GET parameter ?language=en
How to solve this?
function cleanUrl() {
window.location = "http://testpage.pl/?language=en";
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = window.location.href;
if (currentUrl !== cleanedUrl) {
window.location = cleanedUrl;
}
}
cleanUrl();
Your are updating url in first line of function which is causing your code to loop infinite. Remove that line or move to some other function for fix
function cleanUrl() {
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = "http://testpage.pl/?language=en";
if (currentUrl !== cleanedUrl) {
window.location = cleanedUrl;
}
}
cleanUrl();
Keep the window.location assignment as last operation.
function cleanUrl() {
var enUrl = "http://testpage.pl/?language=en";
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = window.location.href;
if( currentUrl !== cleanedUrl ) { enUrl = cleanedUrl; }
window.location = enUrl;
}
I have a script that adds an param to the url when I click the assigned button - next click replaces it with a new param - this work great.
However - now I have three buttons - and I want each button to assign a param to the url - and replacing any params added by any of the other buttons. It also needs to be placed last behind the params that are already there.
so:
(button1) click3: /m4n?ecom-query=imac&seid=etailer-products&viewMode=3?param=grid
(button2) click4: /m4n?ecom-query=imac&seid=etailer-products&viewMode=3?param=list
(button3) click5: /m4n?ecom-query=imac&seid=etailer-products&viewMode=3?param=smalllist
The url before ?param is dynamic and can look different.
$('.click2').on('click', function() {
console.log("Clicked");
var url = window.location.pathname;
var url = window.location.href;
if (url.indexOf('?param=list') > -1) {
url = url.replace("?param=list", "") + '?param=grid'
} else {
url = url.replace("?param=grid", "") + '?param=list'
}
window.location.href = url;
});
How do I do this, I tried to modify my existing script but had no luck.
I think there is a small error in your approach:
All parameters in url should be connected with an &
so now your url should look like that
/m4n?ecom-query=imac&seid=etailer-products&viewMode=3¶m=grid
now if you want to replace old pram, you need to remove the old value also. For that you can use regex as in following code
url = url.replace(/\¶m=.*/,'') + '¶m=list'
So the full code would be:
$('.click2').on('click', function() {
console.log("click2 Clicked");
var url = window.location.href;
url = url.replace(/\¶m=.*/,'') + '¶m=list';
window.location.href = url;
});
Hope it helps
I have the following code to reload page only once after submitting some data using JQuery.
code to reload page :
update: the url here is not ending with '?' because it has parameter value
for example: http://localhost:49208/UserView.aspx?id=12
var url = window.location.href;
if (url.indexOf('?') > -1)
{
window.location.href = url;
}
The problem here is that page reloading does not stop?
The reason it won't stop reloading is because you aren't changing the conditions of the url; so if the if statement is ever true, it will happen again and again.
If you want to reload the page, just use window.location.reload();
Try this logic.
if (url.indexOf('?') == -1) {
url = url + '?';
location = '?';
location.reload(true);
}
Easiest way is to add a flag variable so that javascript can check whether the page is reloaded previously.
var url = window.location.href; // get the current url of page into variable
if (url.indexOf('?') > -1) { // url has a '?'
if(url.indexOf('reloaded') < 0){ // url does not have the text 'reloaded'
url = url + "&reloaded=true"; // add the word 'reloaded' to url
window.location = url; // "reload" the page
}
}
If you want to reload the page only once, use the following method:
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
if(!window.location.hash)
{
window.location = window.location + '#loaded';
window.location.reload();
}
How do I test to see if links are external or internal? Please note:
I cannot hard code the local domain.
I cannot test for "http". I could just as easily be linking to my own site with an http absolute link.
I want to use jQuery / javascript, not css.
I suspect the answer lies somewhere in location.href, but the solution evades me.
Thanks!
I know this post is old but it still shows at the top of results so I wanted to offer another approach. I see all the regex checks on an anchor element, but why not just use window.location.host and check against the element's host property?
function link_is_external(link_element) {
return (link_element.host !== window.location.host);
}
With jQuery:
$('a').each(function() {
if (link_is_external(this)) {
// External
}
});
and with plain javascript:
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (link_is_external(links[i])) {
// External
}
}
var comp = new RegExp(location.host);
$('a').each(function(){
if(comp.test($(this).attr('href'))){
// a link that contains the current host
$(this).addClass('local');
}
else{
// a link that does not contain the current host
$(this).addClass('external');
}
});
Note: this is just a quick & dirty example. It would match all href="#anchor" links
as external too. It might be improved by doing some extra RegExp checking.
Update 2016-11-17
This question still got a lot of traffic and I was told by a ton of people that this accepted solution will fail on several occasions. As I stated, this was a very quick and dirty answer to show the principal way how to solve this problem. A more sophisticated solution is to use the properties which are accessible on a <a> (anchor) element. Like #Daved already pointed out in this answer, the key is to compare the hostname with the current window.location.hostname. I would prefer to compare the hostname properties, because they never include the port which is included to the host property if it differs from 80.
So here we go:
$( 'a' ).each(function() {
if( location.hostname === this.hostname || !this.hostname.length ) {
$(this).addClass('local');
} else {
$(this).addClass('external');
}
});
State of the art:
Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
a.classList.add( location.hostname === a.hostname || !a.hostname.length ? 'local' : 'external' );
});
And the no-jQuery way
var nodes = document.getElementsByTagName("a"), i = nodes.length;
var regExp = new RegExp("//" + location.host + "($|/)");
while(i--){
var href = nodes[i].href;
var isLocal = (href.substring(0,4) === "http") ? regExp.test(href) : true;
alert(href + " is " + (isLocal ? "local" : "not local"));
}
All hrefs not beginning with http (http://, https://) are automatically treated as local
var external = RegExp('^((f|ht)tps?:)?//(?!' + location.host + ')');
Usage:
external.test('some url'); // => true or false
Here's a jQuery selector for only external links:
$('a[href^="(http:|https:)?//"])')
A jQuery selector only for internal links (not including hash links within the same page) needs to be a bit more complicated:
$('a:not([href^="(http:|https:)?//"],[href^="#"],[href^="mailto:"])')
Additional filters can be placed inside the :not() condition and separated by additional commas as needed.
http://jsfiddle.net/mblase75/Pavg2/
Alternatively, we can filter internal links using the vanilla JavaScript href property, which is always an absolute URL:
$('a').filter( function(i,el) {
return el.href.indexOf(location.protocol+'//'+location.hostname)===0;
})
http://jsfiddle.net/mblase75/7z6EV/
You forgot one, what if you use a relative path.
forexample: /test
hostname = new RegExp(location.host);
// Act on each link
$('a').each(function(){
// Store current link's url
var url = $(this).attr("href");
// Test if current host (domain) is in it
if(hostname.test(url)){
// If it's local...
$(this).addClass('local');
}
else if(url.slice(0, 1) == "/"){
$(this).addClass('local');
}
else if(url.slice(0, 1) == "#"){
// It's an anchor link
$(this).addClass('anchor');
}
else {
// a link that does not contain the current host
$(this).addClass('external');
}
});
There are also the issue of file downloads .zip (local en external) which could use the classes "local download" or "external download". But didn't found a solution for it yet.
const isExternalLink = (url) => {
const tmp = document.createElement('a');
tmp.href = url;
return tmp.host !== window.location.host;
};
// output: true
console.log(isExternalLink('https://foobar.com'));
console.log(isExternalLink('//foobar.com'));
// output: false
console.log(isExternalLink('https://www.stackoverflow.com'));
console.log(isExternalLink('//www.stackoverflow.com'));
console.log(isExternalLink('/foobar'));
console.log(isExternalLink('#foobar'));
The benefit of using this approach is that:
It would automatically resolve the hostname for relative paths and fragments;
It works with protocol-relative URLs
To demonstrate this, let's look at the following examples:
const lnk = document.createElement('a');
lnk.href = '/foobar';
console.log(lnk.host); // output: 'www.stackoverflow.com'
const lnk = document.createElement('a');
lnk.href = '#foobar';
console.log(lnk.host); // output: 'www.stackoverflow.com'
const lnk = document.createElement('a');
lnk.href = '//www.stackoverflow.com';
console.log(lnk.host); // output: 'www.stackoverflow.com'
With jQuery
jQuery('a').each(function() {
if (this.host !== window.location.host) {
console.log(jQuery(this).attr('href'));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use is-url-external module.
var isExternal = require('is-url-external');
isExternal('http://stackoverflow.com/questions/2910946'); // true | false
/**
* All DOM url
* [links description]
* #type {[type]}
*/
var links = document.querySelectorAll('a');
/**
* Home Page Url
* [HomeUrl description]
* #type {[type]}
*/
var HomeUrl = 'https://stackoverflow.com/'; // Current Page url by-> window.location.href
links.forEach(function(link) {
link.addEventListener('click', function(e) {
e.preventDefault();
// Make lowercase of urls
var url = link.href.toLowerCase();
var isExternalLink = !url.includes(HomeUrl);
// Check if external or internal
if (isExternalLink) {
if (confirm('it\'s an external link. Are you sure to go?')) {
window.location = link.href;
}
} else {
window.location = link.href;
}
})
})
Internal Link
External Link
This should work for any kind of link on every browser except IE.
// check if link points outside of app - not working in IE
try {
const href = $linkElement.attr('href'),
link = new URL(href, window.location);
if (window.location.host === link.host) {
// same app
} else {
// points outside
}
} catch (e) { // in case IE happens}
Yes, I believe you can retrieve the current domain name with location.href. Another possibility is to create a link element, set the src to / and then retrieving the canonical URL (this will retrieve the base URL if you use one, and not necessarily the domain name).
Also see this post: Get the full URI from the href property of a link
For those interested, I did a ternary version of the if block with a check to see what classes the element has and what class gets attached.
$(document).ready(function () {
$("a").click(function (e) {
var hostname = new RegExp(location.host);
var url = $(this).attr("href");
hostname.test(url) ?
$(this).addClass('local') :
url.slice(0, 1) == "/" && url.slice(-1) == "/" ?
$(this).addClass('localpage') :
url.slice(0, 1) == "#" ?
$(this).addClass('anchor') :
$(this).addClass('external');
var classes = $(this).attr("class");
console.log("Link classes: " + classes);
$(this).hasClass("external") ? googleAnalytics(url) :
$(this).hasClass("anchor") ? console.log("Handle anchor") : console.log("Handle local");
});
});
The google analytics bit can be ignored but this is where you'd probably like to do something with the url now that you know what type of link it is. Just add code inside the ternary block.
If you only want to check 1 type of link then replace the ternaries with an if statement instead.
Edited to add in an issue I came across. Some of my hrefs were "/Courses/" like so. I did a check for a localpage which checks if there is a slash at the start and end of the href. Although just checking for a '/' at the start is probably sufficient.
I use this function for jQuery:
$.fn.isExternal = function() {
var host = window.location.host;
var link = $('<a>', {
href: this.attr('href')
})[0].hostname;
return (link !== host);
};
Usage is: $('a').isExternal();
Example: https://codepen.io/allurewebsolutions/pen/ygJPgV
This doesn't exactly meet the "cannot hardcode my domain" prerequisite of the question, but I found this post searching for a similar solution, and in my case I could hard code my url. My concern was alerting users that they are leaving the site, but not if they are staying on site, including subdomains (example: blog.mysite.com, which would fail in most of these other answers). So here is my solution, which takes some bits from the top voted answers above:
Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
a.classList.add( a.hostname.includes("mywebsite.com") ? 'local' : 'external' );
});
$("a").on("click", function(event) {
if ($(this).hasClass('local')) {
return;
} else if ($(this).hasClass('external')) {
if (!confirm("You are about leave the <My Website> website.")) {
event.preventDefault();
}
}
});
this works for me:
function strip_scheme( url ) {
return url.replace(/^(?:(?:f|ht)tp(?:s)?\:)?\/\/(www\.)?/g, '');
}
function is_link_external( elem ) {
let domain = strip_scheme( elem.attr('href') );
let host = strip_scheme( window.location.host );
return ! domain.indexOf(host) == 0;
}