Using JQuery to display a div based upon a content of URL - javascript

I'm trying to use jQuery so that when somebody goes to this exact page: www.mysite.com/somedirectory/somesubdirectory divwhite appears and divgrey is hidden. This code works. However, I was wondering if there is someway to write the code so that it checks to see if somesubdirectory is two directories lower than the root level and not dependent if somedirectory is there or not in case somedirectory's name changes.
$(document).ready(function() {
var myvariable = $(location).attr('href');
if(myvariable.indexOf("/somedirectory/somesubdirectory") > -1) {
$("#divgrey").hide();
$("#divwhite").show();
}
else {
j$("#divgrey").show();
$("#divwhite").hide();
}
});

You could use one line of vanilla JavaScript
window.location.pathname.split('/').length
If this number equals 3, the path name contains two slashes and you are in a subdirectory two levels below the root directory, independent of their names.
Note that this assumes that you take care of trailing slashes in the URL in your .htaccess.

Related

How to get specific file path name using node js

Is this even possible to get specific file path from url
my file path is like
testing\abc\pqr\subfolder1\anotherFolder
or
testing\sufolder\anothersubfolder\abc\pqr\xyz\mno
my output will look like this
testing\abc\pqr
or
testing\sufolder\anothersubfolder\abc
Its should remove last few name of a folder and provide only specific length folder name from the start of the path which I will pass in an array
You can split the path and just grab the number of segments you want from the front. Since you're showing Windows-style paths, here's some sample code that uses the Windows path separator. This can be adapted to use path.sep if you want a cross platform version. Since your example paths do not start with a leading slash, this code assumes that.
function getFrontPathSegments(fullPath, numSegments) {
let pieces = fullPath.split("\\");
return pieces.slice(0, numSegments).join("\\");
}
// example usage
let front = getFrontPathSegments("testing\\sufolder\\anothersubfolder\\abc\\pqr\\xyz\\mno", 3);
console.log(front);

Load div based on url or ID

I want a certain feature div container-new to load on certain pages only. My theory is to run a if statement on load to say if page url equals /A2017.html or /A2018.html or /A2017.html load <div id="conrainer_new"></div> else don't load.
Is this achievable with JS or jQuery.
I have tried this but div still loads on all urls. im sure there is a better more robust solution to this. also I need to be a able to include multiple urls in the rule.
if (window.location.search..search(/A2017.html))
document.getElementById('conrainer_new').display = 'block'
You can try a similar approach but with using indexOf instead. If the string for the page name is found, indexOf will return the position instead of -1 so the condition will be true.
if (window.location.href.indexOf('/A2017.html') != -1) {
document.getElementById('container_new').display = 'block'
}
As you have multiple values to check for in the URL you can use a regular expression:
if (window.location.match(/\/A2017.html|\/A2018.html/i)
document.getElementById('conrainer_new').display = 'block'
Also note that if there will never be a querystring on the URL you can add $ to the regex to ensure that the match is only at the end of the URL string, eg /\/A2017.html$|\/A2018.html$/i

How to allow for another index string to run a script

I have no script abilitiy, but i'd like to edit an existing script which is currently restricting the script from running on any page other then the one that has a certain string in the URL.
Here is the snippet of the script which limits it from running
if(location.href.indexOf("MODULE=MESSAGE")>0||location.href.indexOf("/message")>0)
This only allows the script to run on these pages
mysite/2014/home/11609?MODULE=MESSAGE1
and the pages range from Message1 to Message20
mysite/2014/home/11609?MODULE=MESSAGE20
I would like to also allow the script to be loaded and ran on these pages
mysite/2014/options?L=11609&O=247&SEQNO=1&PRINTER=1
where the SEQNO=1 ranges from 1 to SEQNO=20, just like the MESSAGE1-MESSAGE20 do
Can someone show me how i can edit that small snippet of script to allow the SEQNO string found in the url to work also.
Thanks
If you can't just remove the condition altogether (there's not enough context to know if that's an option), you can just add another or condition (||) like so:
if(location.href.indexOf("MODULE=MESSAGE")>0
||location.href.indexOf("/message")>0
||location.href.indexOf("SEQNO=")>0)
Note that the second clause there isn't actually being used in any of your examples, so could potentially be removed. Also note that this isn't actually checking for a number so it isn't restricted to Message1 to Message20 as you suggest. It would match Message21 or even MessageFoo. That may or may not be a problem for you. You can make the conditions as restrictive or as lose as makes sense.
If you just want to check for the existence of "SEQNO", simply duplicate what is being done for "MODULE_MESSAGE".
if(location.href.indexOf("MODULE=MESSAGE")>0 ||
location.href.indexOf("SEQNO=")>0 ||
location.href.indexOf("/message")>0)
If you want to also ensure that "MESSAGE" ends in 1-20, and "SEQNO=" ends in 1-20, you can use a regex.
// create the end part of the regex, which checks for numbers 1-20
var regexEnd = "([1-9]|1[0-9]|20)[^0-9]*$";
// create the individual regexes
var messageRegex = new RegExp("MODULE=MESSAGE" + regexEnd);
var seqnoRegex = new RegExp("SEQNO=" + regexEnd);
// now comes your if statement, using the regex test() function, which returns true if it matches
if(messageRegex.test(location.href) ||
seqnoRegex.test(location.href) ||
location.href.indexOf("/message")>0)

JavaScript To Strip Page For URL

We have a javascript function we use to track page stats internally. However, the URLs it reports many times include the page numbers for search results pages which we would rather not be reported. The pages that are reports are of the form:
http://www.test.com/directory1/2
http://www.test.com/directory1/subdirectory1/15
http://www.test.com/directory3/1113
Instead we'd like the above reported as:
http://www.test.com/directory1
http://www.test.com/directory1/subdirectory1
http://www.test.com/directory3
Please note that the numbered 'directory' and 'subdirectory' names above are just for example purposes and that the actual subdirectory names are all different, don't necessarily include numbers at the end of the directory name, and can be many levels deep.
Currently our JavaScript function produces these URLs using the code:
var page = location.hostname+document.location.pathname;
I believe we need to use the JavaScript replace function in combination with some regex but I'm at a complete loss as to what that would look like. Any help would be much appreciated!
Thanks in advance!
I think you want this:
var page = location.href.substring(0,location.href.lastIndexOf("/"));
You can use a regex for this:
document.location.pathname.replace(/\/\d+$/, "");
Unlike substring and lastIndexOf solutions, this will strip off the end of the path if it consists of digits only.
What you can do is find the last index of "/" and then use the substring function.
Not sure you need a regex if you're just pulling off the last slash + content.
http://www.w3schools.com/jsref/jsref_lastIndexOf.asp
I'd probably use that to search for the last "/" character, then do a substring from the start of the string to that index.
How about this:
var page = location.split("/");
page.pop();
page = page.join("/");
I would think you need to use the .htaccess with rewrite rules to change the look of the url, however I am still looking to see if this is available to javascript. Will repost when I find out more
EDIT*
the lastIndexOf would only give you the position, therefor you would still need to replace. ex:
var temp = page.substring(page.lastIndexOf("/"),page.length-1);
page = page.replace(temp, "");
unfortunately I'm not that advanced in my coding so there is probably more efficient coding in the other answers. Sorry for any inconveniences with my initial answer.

Why does my if condition prevent either clause from executing?

I'm trying to re-write the URLs of a set of links that I select using a jQuery class selector. However, I only wish to re-write the links that don't already have a href attribute specified, so I put in an if/else construct to check for this... However, it's not working. It does work without the if else statement so I'm pretty sure that is where I screwed up. I'm new to both JavaScript and jQuery so sorry if my question is elementary and/or overly obvious.
var url = window.location;
var barTwitter = $("a.shareTwitter").attr('href');
if (barTwitter).val() == "null") {
$("a.barTwitter").attr('href','http://www.twitter.com/home?status='+ url +'');
} else {
$("a.barTwitter").attr('href',barTwitter);
}
if (barTwitter).val() == "null") {
This is syntactically invalid (count the parentheses!). You rather want to do:
if (barTwitter.val() == "null") {
Further, the val() function only works on input elements which are wrapped by jQuery, not on element attribute values which are at end just normal variables. You rather want to compare normal variables against the literal null:
if (barTwitter == null) {
There are actually a few problems with your code... BalusC correctly describes the first one - syntax errors in your if condition - but you should probably consider some of the rest...
I'll start with your code corrected according to BalusC's answer, with comments added to describe what's happening:
var url = window.location; // obtain the URL of the current document
// select the href attribute of the first <a> element with a shareTwitter class
var barTwitter = $("a.shareTwitter").attr('href');
if (barTwitter == null) { // if that attribute was not specified,
// set the attribute of every matching element to a combination of a fixed URL
// and the window location
$("a.barTwitter").attr('href','http://www.twitter.com/home?status='+ url +'');
} else {
// set the attribute of every matching element to that of the first
// matching element
$("a.barTwitter").attr('href',barTwitter);
}
Other issues with your code
Ok... now the problems:
jQuery matches sets - a single selector can potentially match multiple elements. So if there are multiple links on the page with the shareTwitter class, you'll be pulling the href attribute for the first one, but changing all of them. That's probably not what you want, although if there is only a single link with that class then you don't care.
In the else clause, you're not actually modifying the href at all... Unless you have multiple matching links, in which case you'll change all of them such that they have the href of the first one. Again, probably not what you want, although irrelevant if there is only one link... So, in the best-case scenario, the else clause is pointless and could be omitted.
You can actually omit the if/else construct entirely: jQuery allows you to test for the existence of attributes in the selector itself!
You're including the URL of the current page in the querystring of your new, custom URL - however, you're not properly escaping that URL... This could cause problems, as full URLs generally contain characters that are not strictly valid as part of URL querystrings.
Notes on working with JavaScript
A quick aside: if you plan on doing any development using JavaScript, you should obtain some tools. At minimum, install Firebug and familiarize yourself with the use of that and JSLint. The former will inform you of errors when the browser fails to parse or execute your code (in addition to many, many other useful debugging and development tasks), and the latter will check your code for syntax and common style errors: in this case, both tools would have quickly informed you of the initial problems with your code. Instructing you in the proper use of these tools is beyond the scope of this answer, but trust me - you owe it to yourself to take at least a few hours to read up on and play with them.
Toward safer code
Ok, back to the task at hand... Here's how I would re-write your code:
var url = window.location; // obtain the URL of the current document
// escape URL for use in a querystring
url = encodeURIComponent(url);
// select all <a> elements with a shareTwitter class and no href attribute
var twitterLinks = $("a.shareTwitter:not([href])");
// update each selected link with a new, custom link
twitterLinks.attr('href', 'http://www.twitter.com/home?status='+ url +'');
Note that even though this new code accomplishes the same task, it does so while avoiding several potential problems and remaining concise. This is the beauty of jQuery...
firs of all your syntax is screwed up: if (barTwitter).val() == "null") should be if (barTwitter.val() == "null") or if ((barTwitter).val() == "null")
Secondly barTwitter is either going to be a string or null so you cant call val which is a jQuery Object method specific to input elements.
Lastly you probably dont want to compare to null because it possible the value will be an empty string. Thus its better to use length property or some other method. A sample with lenght is below.. but im not sure what attr returns if if ther eis no value... check the docs.
var url = window.location;
var barTwitter = $("a.shareTwitter").attr('href');
if (barTwitter.length < 1) {
$("a.barTwitter").attr('href','http://www.twitter.com/home?status='+ url +'');
} else {
$("a.barTwitter").attr('href',barTwitter);
}

Categories