How to call a function with href to other page on HTML - javascript

So I have 3 links: 1, 2 and 3 and they all go to the same page and each have a function (1(), 2() and 3()) I want to, when you go to one of those pages from the home page, to go to the 123.html and run 1() or 2() depending on what button they clicked.
I've tried this:
<li><span>Link1</span></li>
But it didn't run the function at all. And I want to have all of them like this:
<li><span>Link1</span></li>
<li><span>Link2</span></li>
<li><span>Link3</span></li>

You cannot pass javascript to a page like this unless the page you are going to is looking for the javascript query string in the url.
It would be better to send a query string variable such as ?action=Link1 and then have some javascript check for the "action". You could then run a function based on what the action is.
There are a lot of functions you can find that will do this for you, by looking at the window.location variable

This is not the way of doing.
What you could do is add a parameter in your link, something like
?function:1.
You can then extract the parameter on your 123.html page like this :
var url_string = window.location.href
var url = new URL(url_string)
var c = url.searchParams.get("function")
c will have the value of 1, 2 or 3. With that you can make a switch statement and select which function to execute :
switch(c) {
case 1:
function1()
break
}
I do not recommend working like this but if you want to do it like that here you go.

Based on a similar question you can't (1st answer), but expanding on this answer you can do something like this
a.html
<li><span>Link1</span></li>
b.html
<script>
// get hash from url
var hash = window.location.hash;
// clean
hash = hash.replace('#', '');
hash = hash.replace(';', '');
hash = hash.replace(new RegExp("%20", "g"), "");
const fb = (a, b) => {
console.log(a);
console.log(b);
}
// Option 1:
/**
* parse all parameters from string to an array
*/
const parseParams = (str) => {
let params = str.split(/[/(/)]/)[1].split(',');
for (i=0; i < params.length; i++) {
params[i] = params[i].replace(new RegExp("'", "g"), "");
}
return params;
}
// check for existing function - parse only the function name
switch(hash.substring(0, hash.indexOf("("))) {
case "fb":
var params = parseParams(hash);
fb(...params);
break;
default:
break
}
// Option 2 (easy solution but try to avoid this):
eval(hash);
</script>

Related

Modifying HTTP GET Request via Select Menu Change - Update Parameter

I have a search results page in a PHP site that returns a list of results using pagination. The URL looks like this:
findProducts.php?action=searchAssets&orderNumber=xxxx&productName=zzz&skip=20
I have a select menu that allows the user to modify/filter the search results which triggers a script like this:
$(document).ready(function() {
$('#productType').change(function() {
window.location.href = window.location.href + '&productType=' + $(this).val();
});
});
This is working well except for one thing - I need to reset the 'skip' parameter to 0 for the new filter search as the pagination values from the previous search won't be valid or applicable. Is there a way I can change:
skip=20
to:
skip=0
as part of this script?
You could do a RegExp replace on the URL:
window.location.href = window.location.href.replace(/((?:\?|&)skip)=\d+/, '$1=0') + '...';
(untested)
Note that you should do the same with the productType because otherwise you'll add it again and again.
Better solution would possibly be to have a base URL and then add all necessary parameters instead of doing search and replace...
You can get the query from the URL by splitting the URL using ?
This will give you the base url in the first index and the query in the second.
You can then get the query parameters by splitting the query using &.
You can loop through all of the parameters checking if it is the skip parameter. If the parameter is the skip parameter push your new value to an output array. Otherwise push the unchanged parameter to an output array.
You can then use join to join all of your output elements using & to reconstruct the query and return your original base url with your new query string.
<script>
function fixQuery(qstr) {
var parts = qstr.split('?');
var query = parts[1];
var a= query.split("&");
var out=[];
for (var i = 0; i < a.length; i++) {
var b = a[i].split('=');
if(decodeURIComponent(b[0])=="skip")
{
out.push("skip=0")
}
else {
out.push(a[i]);
}
}
return parts[0] + '?' + out.join("&");
}
var result= fixQuery("http://example.com/findProducts.php?param1=test+thing&param2=hello&skip=10");
console.log(result)
//http://example.com/findProducts.php??param1=test+thing&param2=hello&skip=0
</script>

Getting query string parameters from clean/SEO friendly URLs with JavaScript

I've recently switched my site to use clean/SEO-friendly URLs which has now caused me some issues with a JavaScript function I had for grabbing the query string parameters.
Previously I had been using this function:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
Which worked fine on things like this as you could just call getQueryVariable("image") and return "awesome.jpg".
I've been playing with the indexOf(); function to try and grab the relevant parameters from the current URL, eg:
var url = window.location.pathname;
var isPage = url.indexOf("page") + 1;
In an attempt to get the array index number of the "page" parameter, and then plus 1 it to move along to the value of that (?page=name > /page/name/)
JavaScript isn't my main language, so I'm not used to working with arrays etc and my attempt to turn this into a new function has been giving me headaches.
Any pointers?
How about something like this? It splits the path and keeps shifting off the first element of the array as it determines key/value pairs.
function getPathVariable(variable) {
var path = location.pathname;
// just for the demo, lets pretend the path is this...
path = '/images/awesome.jpg/page/about';
// ^-- take this line out for your own version.
var parts = path.substr(1).split('/'), value;
while(parts.length) {
if (parts.shift() === variable) value = parts.shift();
else parts.shift();
}
return value;
}
console.log(getPathVariable('page'));
This can be done formally using a library such as router.js, but I would go for simple string manipulation:
const parts = '/users/bob'.split('/')
const name = parts[parts.length - 1] // 'bob'

Adding parameters to url

I try to test the function s.Util.getQueryParam.
The url I have is in format
http://project1/project1.html
I would like to add some parameters in the url after that in order to have something like this format
http://project1/project1.html/?id=03
I try to use this example
// www.mysite.com/my_app.html?Use_Id=abc
var GET = {};
var query = window.location.search.substring(1).split("&");
for (var i = 0, max = query.length; i < max; i++)
{
if (query[i] === "") // check for trailing & with no param
continue;
var param = query[i].split("=");
GET[decodeURIComponent(param[0])] = decodeURIComponent(param[1] || "");
}
I try to add in Get this id=03 but it is not working when I refresh my browser I can't see the parameter. Is it possible to help me how can I run it with the right way?
You can modify window.location.search to add query parameters. This will cause the browser to load the new URL (the page will be refreshed).
Example: window.location.search = '?id=03'.

Search URL parameters with Angular JS

Say I have a URL like this:
www.mysite.com?account=23&token=asdu756sdg65sdf
Now, I need to access those URL parameters individually using Angular JS.
I've tried using location.search inside my controller:
console.log(location.search);
Which nicely returns the full query string:
?account=23&token=asdu756sdg65sdf
But it seems to return a string, not an object. Is there an easy way to access the individual ids and values in the string?
I've also tried:
console.log($location.search());
Which seems to return an empty object.
Try with
var account = ($location.search()).account;
but the url should be like /#!/?account=1
have your tried using it as a function instead?
$location.search();
pure js way:
var getParamFromURL = function(_url) {
var url = _url;
var _paraString = url.indexOf("&") > -1 ? url.substring(url.indexOf("?") + 1, url.length).split("&") : url.substring(url.indexOf("?") + 1, url.length).split('');
var _paraObj = {};
for (i = 0; p = _paraString[i]; i++) {
_paraObj[p.substring(0, p.indexOf("=")).toLowerCase()] = p.substring(p.indexOf("=") + 1, p.length);
}
return _paraObj;
}
via angular js:
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
Great. #Cooper is right.

Remove character from div id

I need to remove the tag within this div id. What am I doing wrong here?
function thanksForHelping(div){
var siblingOne = $(div).next();
var siblingTwo = $(div).next().next();
var NIDsiblingOne = siblingOne.substring(1);
var NIDsiblingTwo = siblingTwo.substring(1);
}
I want to see:
siblingOne == #yo
siblingTwo == #hi
NIDsiblingOne == yo
NIDsiblingTwo == hi
However I am receiving this error in my console:
TypeError: siblingOne.substring is not a function
.next() returns a jQuery object (docs), which is why you cannot call substring() on it. If you want the id, you need to use attr() or prop():
$(div).next().attr('id'); // or prop()
although it's a little unclear exactly what you're going for, but hopefully this should point you in the right direction.
It looks like you're saying you have some div like <div id="#myid"> This is incorrect. You shouldn't have the # in the id; that's just how it's referenced in CSS queries.
But, you could be using links to link to that div like this: <a href="#myid"> in which case you would want to strip the # to get the proper value if you were going to target with something like getElementById()
Even so, you're calling substring on a jQuery object, not on the id itself. Try something like:
function thanksForHelping(div){
var siblingOne = $(div).next(), siblingTwo = siblingOne.next();
var existingIdOne = siblingOne.attr("id");
var existingIdTwo = siblingTwo.attr("id");
var noHashIdOne = existingIdOne.replace(/^#/, ''); //Using regex here in case it doesn't actually have a leading #
var noHashIdTwo = existingIdOne.replace(/^#/, '');
}
If you were doing the link thing that I mentioned before, you'd have two ways to approach it: 1) Fetch the actual id like I show above, or use jQuery and just use the version with the hash. So, something like this:
function elementsForIntraPageLinks(){
var links = $("a.internal");
links.each(function(i, link) {
var href = link.href;
var targetElement = $(href);
console.log("targetElement:", targetElement);
});
}
or without jQuery but in a modern browser:
function elementsForIntraPageLinks(){
var links = document.querySelectorAll('a[href^="#"]');
links.forEach(function(link, i, links) {
console.log("targetElement:", document.querySelector(link.href));
});
}
or in a slightly older browser
function elementsForIntraPageLinks(){
var links = document.getElementsByTagName('a'), i, ii, link;
for(i = 0, ii = links.length; i < ii; i++){
link = links[i];
if (/^#/.test(link.href)) {
console.log("targetedElement", document.getElementById(link.href.replace(/^#/, ""));
}
});
}

Categories

Resources