How to Execute Javascript Code Using Variable in URL - javascript

I'm really new to Javascript and I'm having some trouble understanding how to get the following to work. My goal is to have a certain Javascript action execute when a page loads and a variable added to the end of the URL would trigger which Javascript action to execute. The URL of the page that I'm looking to implement this on is http://www.morgantoolandsupply.com/catalog.php. Each of the "+expand" buttons, which are Javascript driven, drop-down a certain area of the page. Ultimately, I would like to be able to create a URL that would automatically drop-down a certain category when the page loads. Could anybody explain to me the process to do this? Thanks in advance for any help!

You have to parse the URL somewhat "manually" since the parameters in the url aren't automatically passed to javascript, like they are in server-side scripting (via $_GET in PHP, for instance)
One way is to the use the URL fragment identifier, i.e. the "#something" bit that can go at the end. This is probably the neatest way of doing it, since the fragment isn't sent to the server, so it won't be confused with any other parameters
// window.location.hash is the fragment i.e. "#foo" in "example.com/page?blah=blah#foo"
if( window.location.hash ) {
// do something with the value of window.location.hash. First, to get rid of the "#"
// at the beginning, do this;
var value = window.location.hash.replace(/^#/,'');
// then, if for example value is "1", you can call
toggle2('toggle' + value , 'displayText' + value);
}
The URL "http://www.morgantoolandsupply.com/catalog.php#1" would thus automatically expand the "toggle1" element.
Alternatively, you can use a normal GET parameter (i.e. "?foo=bar")
var parameter = window.location.search.match(/\bexpand=([^&]+)/i);
if( parameter && parameter[1]) {
// do something with parameter[1], which is the value of the "expand" parameter
// I.e. if parameter[1] is "1", you could call
toggle2('toggle' + parameter[1] , 'displayText' + parameter[1]);
}
window.location.search contains the parameters, i.e. everything from the question mark to the end or to the URL fragment. If given the URL "example.com/page.php?expand=foo", the parameter[1] would equal "foo". So the URL "http://www.morgantoolandsupply.com/catalog.php?expand=1" would expand the "toggle1" element.
I'd perhaps go for something more descriptive than just a number in the URL, like, say use the title of the dropdown instead (so "#abrasives" or "expand=abrasives" instead of "#1" or "expand=1"), but that would require a little tweaking of your existing page, so leave that for later

You've already got the function to call: toggle2(), which takes two parameters that happen to be identical for all categories except for a number at the end. So create a URL that includes that number: http://www.morgantoolandsupply.com/catalog.php#cat=4
Then find that number in location.hash using a regular expression. This one is robust enough to handle multiple url parameters, should you decide to use them in the future: /[\#&]cat=(\d+)/. But, if you expect to never add anything else to the url, you could use a very simple one like /(\d+)/.
Once you've got the number, it's a simple matter of using that number to create your two parameters and calling toggle2().
This should work:
window.onload = function() {
if (/[\#&]cat=(\d+)/.test(location.hash)) {
var cat = parseInt(RegExp.$1);
if (cat > 0 && cat < 13) {
toggle2("toggle"+cat, "displayText"+cat);
}
}
}

Not a complete answer ("Give a man a fish" and all that), but you can start with something along these lines:
// entire URL
var fullURL = window.location.href;
// search string (from "?" onwards in, e.g., "www.test.com?something=123")
var queryString = window.location.search;
if (queryString.indexOf("someParameter") != -1) {
// do something
}
More info on window.location is available from the Mozilla Developer Network.
Having said that, given that you're talking about a PHP page why don't you use some server-side PHP to achieve the same result?

Related

var dataString = \'search=\'+ searchid; - jquery

I'm new to jQuery and I am trying to understand a bit of code to be able to apply a similar concept in my coursework.
$(function(){
$(".search").keyup(function() {
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\') {
}
});
})(jQuery);
What is the dataString variable trying to do?
There are quite a few things that seem "off" with this snippet of code, which I'll address below.
What is this code doing?
It looks like some basic functionality that might be used to build a search querystring that is passed onto some AJAX request that will search for something on the server.
Basically, you'll want to build a string that looks like search={your-search-term}, which when posted to the server, the search term {your-search-term} can be easily identified and used to search.
Noted Code Issues
As mentioned, there are a few issues that you might want to consider changing:
The Use of Escaped Quotes (i.e. \') - You really don't need to escape these as they aren't present within an existing string. Since you are just building a string, simply replace them with a normal ' instead. Without knowing more about your complete scenario, it's difficult to advise further on this.
Checking String Length - Your existing code once again checks if the searchId is an empty string, however you may want to consider checking the length to see if it actually empty via searchId.length != 0, you could also trim this as well (i.e. searchId.trim().length != 0).
Consider A Delay (Optional) - At present, your current code will be executed every time a key is pressed, which can be good (or bad) depending on your needs. If you are going to be hitting the server, you may consider adding a delay to your code to ensure the user has stopped typing before hitting the server.
You can see some of these changes implemented below in the annotated code snippet:
// This is a startup function that will execute when everything is loaded
$(function () {
// When a keyup event is triggered in your "search" element...
$(".search").keyup(function () {
// Grab the contents of the search box
var searchId = $(this).val();
// Build a data string (i.e. string=searchTerm), you didn't previously need the
// escaping slashes
var dataString = 'search=' + searchId;
// Now check if actually have a search term (you may prefer to check the length
// to ensure it is actually empty)
if(searchId.length != 0) {
// There is a search, so do something here
}
}
}

Change the pathname in the URL of a link while keeping the querystring constant

From a page with the following URL, http://example.com/foo.html?query=1&other=2, I want to create a link to http://example.com/bar.html?query=1&other=2. How do I do that without explicitly saving and reloading all the query strings.
I need this to easily link from an iframe version of a page (embed.html?query) to the full page (index.html?query).
I would have recommended using the Location object's search method (available at document.location or window.location) to pull out the parameters, then modify the rest of the URL, but that API is apparently specific to Firefox.
I would simplify #DMortensen's answer by just splitting on the first ?, then modifying the first part (which will be the URL's path portion only), and reapplying the second part.
If you need to parse the parameters, I recommend the jQuery plugin Query Parameter Parser: one call to $.parseQuery(s) will pull out an object of all the keys & values.
It can be finicky, but you could split the URI on '?' and then loop through the 2nd element of that array to grab the key/val pairs if you need to evaluate each pair (using '&' as a delimiter). The obvious weakness in this would be if there are additional '?' or '&' used in the URI.
Something like this maybe? (pseudocode-ish)
var URI = document.URL;
var qs = URI.split('?');
var keyvalpair = qs[1].split('&');
var reconstructedURI = '&' + keyvalpair;
for(var i = 0; i< keyvalpair.length; i++){
var key = keyvalpair[i].split('=')[0];
var val = keyvalpair[i].split('=')[1];
}
Thank you for all the answers. I tried the following and it works.
function gotoFullSite() {
var search = window.location.search;
window.open("http://example.com/"+search)
}
$('#clickable').click(gotoFullSite);
and then use <a id = "clickable" href="#"></a>. When I click the link, it opens the proper website with all the query parameters in a new tab. (I need a new tab to break out of an iframe.)

Add body #id based on url

Need help! I've been looking for a solution for this seemingly simple task but can't find an exact one. Anyway, I'm trying to add custom #id to the tag based on the page's URL. The script I'm using works ok when the URLs are like these below.
- http://localhost.com/index.html
- http://localhost.com/page1.html
- http://localhost.com/page2.html
-> on this level, <body> gets ids like #index, #page1, #page2, etc...
My question is, how can I make the body #id still as #page1 or #page2 even when viewing subpages like this?
- http://localhost.com/page1/subpage1
- http://localhost.com/page2/subpage2
Here's the JS code I'm using (found online)
$(document).ready(function() {
var pathname = window.location.pathname;
var getLast = pathname.match(/.*\/(.*)$/)[1];
var truePath = getLast.replace(".html","");
if(truePath === "") {
$("body").attr("id","index");
}
else {
$("body").attr("id",truePath);
}
});
Thanks in advance!
edit: Thanks for all the replies! Basically I just want to put custom background images on every pages based on their body#id. >> js noob here.
http://localhost.com/page2/subpage2 - > my only problem is how to make the id as #page2 and not #subpage2 on this link.
Using the javascript split function might be of help here. For example (untested, but the general idea):
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
$('body').id = segments[0];
Also, you might want to consider using classes instead of ID's. This way you could assign every segment as a class...
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
for (var i = 0; i < segments.length; i++) {
$('body').addClass(segments[i]);
}
EDIT:
Glad it worked. Couple of notes if you're planning on using this for-real: If you ever have an extension besides .html that will get picked up in the class name. You can account for this by changing that replace to a regex...
var url = window.location.href.replace(/http[s]?:\/\//, '');
// Trim extension
url = url.replace(/\.(htm[l]?|asp[x]?|php|jsp)$/,'');
If there will ever be querystrings on the URL you'll want to filter those out too (this is the one regex I'm not 100% on)...
url = url.replace(/\?.+$/,'');
Also, it's a bit inefficient to have the $('body') in every for loop "around" as this causes jQuery to have to re-find the body tag. A more performant way to do this, especially if the sub folders end up 2 or 3 deep would be to find it once, then "cache" it to a variable like so..
var $body = $('body');
for ( ... ) {
$body.addClass( ...
}
Your regex is only going to select the last part of the url.
var getLast = pathname.match(/./(.)$/)[1];
You're matching anything (.*), followed by a slash, followed by anything (this time, capturing this value) and then pulling out the first match, which is the only match.
If you really want to do this (and I have my doubts, this seems like a bad idea) then you could just use window.location.pathname, since that already has the fullpath in there.
edit: You really shouldn't need to do this because the URL for the page is already a unique identifier. I can't really think of any situation where you'd need to have a unique id attribute for the body element on a page. Anytime where you're dealing with that content (either from client side javascript, or from a scraper) you should already have a unique identifier - the URL.
What are you actually trying to do?
Try the following. Basically, it sets the id to whatever folder or filename appears after the domain, but won't include a file extension.
$(document).ready(function() {
$("body").attr("id",window.location.pathname.split("/")[1].split(".")[0]);
}
You want to get the first part of the path instead of the last:
var getFirst = pathname.match(/^\/([^\/]*)/)[1];
If your pages all have a common name as in your example ("page"), you could modify your script including changing your match pattern to include that part:
var getLast = pathname.match(/\/(page\d+)\//)[1];
The above would match "page" followed by a number of digits (omitting the 'html' ending too).

How do I concatenate a string with a variable?

So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!

Get URL parameters and insert into form action url with javascript

I have an html page that people access using an affiliate link, so it has affiliate code in the url (http://www.site.com?cmpid=1234&aid=123). I want to add the cmpid and the aid to the form action url (so when submitted, it submits to the url /form.aspx but adds the cmpid and aid to the end, ie: form.aspx?cmpid=1234&aid=123).
I have no other option than javascript. I can't make this page php or aspx.
window.onload = function() {
var frm = document.forms[0];
frm.action = frm.action + location.search;
}
You can get access to the query string by location.search. Then you should be able to append it onto the form's action directly, something like the following:
// Get a reference to the form however, such as document.getElementById
var form = ...;
// Get the query string, stripping off the question mark (not strictly necessary
// as it gets added back on below but makes manipulation much easier)
var query = location.search.substring(1);
// Highly recommended that you validate parameters for sanity before blindly appending
// Now append them
var existingAction = form.getAttribute("action");
form.setAttribute("action", existingAction + '?' + query);
By the way, I've found that modifying the query string of the form's action directly can be hit-and-miss - I think in particular, IE will trim off any query if you're POSTing the results. (This was a while ago and I can't remember the exact combination of factors, but suffice to say it's not a great idea).
Thus you may want to do this by dynamically creating child elements of the <form> that are hidden inputs, to encode the desired name-value pairs from the query.

Categories