Show content on certain URL - javascript

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.

Related

Attempting window.location or window.location.href redirect which is causing a loop

I'm attempting to use javascript to determine if the user is using a certain language and if they're not using english then for the page to load a different page BUT with the params of which I've grabbed from the url.
I have been able to load the page with the params but I keep falling into a loop reloading the page, even after skimming through the countless other examples, such as: this or this.
function locateUserLanguage() {
var languageValue = (navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage)).split('-');
var url = window.location.href.split('?');
var baseUrl = url[0];
var urlParams = url[1];
if (languageValue[0] === 'en') {
console.log('no redirect needed, stay here.');
} else {
// I tried to set location into a variable but also wasn't working.
// var newURL = window.location.href.replace(window.location.href, 'https://www.mysite.dog/?' + urlParams);
window.location.href = 'https://www.mysite.dog/?' + urlParams
}
} locateUserLanguage();
I've attempted to place a return true; as well as return false; but neither stop the loop.
I've tried window.location.replace(); and setting the window.location.href straight to what I need, but it's continuing to loop.
There is a possibility that the script in which this function is written is executed in both of your pages (english and non-english) on load. So, as soon as the page is loaded, locateUserLanguage function is executed in both english and non-english website causing the infinite loop.
You need to put a check before you call locateUserLanguage function.
Suppose english website has url = "www.myside.com" and non-english website has url "www.myside.aus". So the condition needs to be
if (window.location.host === "www.myside.com") { locateUserLanguage() }
This will make sure that locateUserLanguage is called only in english website.
Or other apporach can be to load this script only in english website which will avoid the usage of conditional statement.
Hope it helps. Revert for any doubts.

JS/Jquery way to determine if the user entered page from another site

I am attempting to write a script that would launch a modal if the user enters a page from any external link. I am assuming the document.referrer is the way to do it, but not familiar enough with JS as to how to implement it in an "if" conditional. Any suggestions are appreciated.
I'm assuming it would look something like this?
if (document.referrer !== window.location.hostname) {
// do something
}
If you would like to check if the user entered a page from an external link, you can parse the document.referrer to get just the hostname, and compare that with window.location.hostname:
var parser = document.createElement('a');
parser.href = document.referrer;
var isExternallyReferred = document.referrer.length > 0 && parser.hostname !== window.location.hostname;
if (isExternallyReferred) {
// launch modal
}

Is it possible to disable a javascript IF statement for a specific page

A javascript with "IF" statement written in all pages header template and which is unnecessary only for a specific page, is it possible to disable that statement for a specific page. Below is the javascript which make external links to open in new tab, can i disable this small script only for a google custom search page because the result links have google(external) url which redirects to website(internal), that's why script is reading links as external. Or is there some better way than disabling the if statement? If anyone knows how to solve this problem, please help
Javascript:
$(document).ready(function() {
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href)) {
$(this).attr("target", "_blank");
}
});
});
One way to do it for multiple pages, like this:
var excludedPages = ['blockpage1.html', 'blockpage2.html'];
for (var i = 0; i < excludedPages.length; i++) {
if (location.href.indexOf(excludedPages[i]) !== -1) {
// do something if page found
console.log("this page is blocked for extra code");
} else {
// do something if page not found in the list
console.log("this page is not included in block list");
}
}
EDIT
Note: The only thing to be aware of with JavaScript, it is running on client side (browser side) and any one with basic web development knowledge are able to change the block site or edit any the site content. This make it possible getting access to what ever site that was blocked. So it all depends how important your blocking mechanism and strategy.
Probably the easiest way would be to set a flag variable on the custom search page above the script, for example:
var keepInternal = true;
And then modify one line in your script to check for that flag:
$(document).ready(function() {
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href) && !keepInternal) {
$(this).attr("target", "_blank");
}
});
});

how to check if you are on a certain page in jquery mobile

I would like to know if it is possible if test which page you are on using jquery mobile and based on that page do whatever you need to. Here is the code I was using:
if(window.location.href == '#searchpage')
{
$("#searchtitle").val($(this).attr('titleResult'));
$("#searchauthor").val($(this).attr('authorResult'));
$("#searchpublisher").val($(this).attr('publisherResult'));
$( "#searchedition" ).val($(this).attr('editionResult'));
$("#searchDetailsSearchResults").empty();
}
i.e. if I am on the page called searchpage then we would fill in text boxes with certain values. As such I'm struggling to find a way to determine if I am on a given page? How would I achieve this?
you are looking for $.mobile.activePage
if $.mobile.activePage.attr("id") == "searchpage" // do stuff
Fetch current url using pure JS:
var current_url = window.location.pathname;
Fetch current url using jQuery:
var current_url = $(location).attr('href');
If you're looking for the page title instead of url:
var current_title = $(document).attr('title');
Then you would simply use that to check if you're on the expected page:
var current_title = $(document).attr('title');
if (current_title == "Home") {
console.log("on the homepage");
}

How can I tell if a user is on index.html?

I use document.URL to detect if a user is on index.html:
if(document.URL.indexOf("index") >-1) return true;
But if the user types "mydomain.com" or "mydomain.com/" then the test returns false.
I could try:
if(document.URL ==="http://myDomain.com") return true;
But I want to use this code on different domains. Any suggestions?
There are so many permutations of URL that could mean that a user is on index.html. Instead could you not put a var within that file:
<script type="text/javascript">
on_index = true;
</script>
Just check if on_index is not undefined and is true. That'll be accurate 100% of the time.
javascript Location object has many useful properties, in particular, you can examine location.pathname.
Basically, you're on the "index" page if the pathname is 1) empty 2) is equal to a slash / 3) starts with index or /index.
var p = window.location.pathname;
if (p.length === 0 || p === "/" || p.match(/^\/?index/))
alert ("on the index page!")
See Javascript .pathname IE quirk? for the discussion of leading slash issues.
There isn't a direct link between files and URLs. Additionally, index.html does not need to be in the site's root and the default page does not need to be index.html.
If you want a generic solution, you're probably out of luck. If you want a solution for your particular case, you can just provide that info from the page itself, e.g. defining an ID or class name:
<body class="index">
... or a JavaScript variable:
// Pick one
var page = 'index';
var isIndex = true;
If all you want is some simple string manipulation with current location, grab the pathname property of the window.location object:
// Untested
if( window.location.pathname=="/" || window.location.pathname=="/index.html" ){
}
You could use
if (document.location.pathname === '/' ||
document.location.pathname.indexOf('index') >-1 ) {
return true;
}
If you have access to the actual page and not just the script then you should follow #Ben Everard's advice.
Just make sure you include the snippet he proposes before your script..

Categories

Resources