I have a javascript on my server, and i need to set a value / calling a function inside the javascript when calling a URL. Is there anyway of doing that ?
UPDATE:
<script type="application/x-javascript" src="test-test.js"></script>
Thats how it its loaded on the HTML site. And I want to call the function test(e,e) inside test-test.js, by putting in the URL in a browser with some values for e,e..
Unless you are using one of the few web servers that employs server-side JavaScript, your script is going to run in the browser after the page is loaded. If you want to include information from the URL in your script (and this assumes that you can use a query string without changing the server's behavior), you can use window.location.search to get everything from the question mark onwards.
This function will return either the entire query string (without the question mark) or a semicolon-delimited list of values matching the name value you feed it:
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
So if the URL was, say:
http://www.yoursite.com/somepage.html?name=John%20Doe&occupation=layabout
if you call getUrlQueryString() you would get back name=John Doe&occupation=layabout. If you call getUrlQueryString("name"), you would get back John Doe.
(And yes, I like banner-style indents. So sue me.)
You can use address plugin to be able to pass some condition in urls trough # symbol: http://my_site/my_page#your_condition
in the html you can write something like this:
<script>
$(function(){
// Init and change handlers
$.address.init().change(function(event) {
if (event.value == "your_condition")
run_my_finction();
});
)};
<script>
See this exaple for the futher help.
If you want to execute JavaScript from the browsers' address bar, you can use a self-invoking function:
javascript:(function () {
alert('Hello World');
/* Call the JavaScript functions you require */
})();
Related
I have a question, i wanted to know if there is a way to call a specific function if a specific page URL is opened?
#shop_modal is in http://myurl/liste-boutique.php
#dep_modal is in http://myurl/index.php
Right now, i have Error when i try to open the #dep_modal because JS cant find #shop_modal on that page same page, so it does not execute below that.
I think AJAX can help figuring this out, otherwise i will have to split the code in 2 JS files, which i don't want to
const new_shop = $("#new_shop")[0];
const save_shop = $("#shop_form")[0];
const close_shop_modal = $("#close_shop_modal")[0];
const new_departement = $("#new_dep")[0];
const save_departement = $("#dep_form")[0];
const close_dep_modal = $("#close_dep_modal")[0];
// I want this to be called if the URL is http://my-URL/liste-boutique.php
new_shop.addEventListener('click', function(){
$("#shop_modal")[0].style.visibility = "visible";
})
// I want this to be called if the URL is http://my-URL/index.php
new_departement.addEventListener('click', function(){
$("#dep_modal")[0].style.visibility = "visible";
})
i need to ask question, but i don't know what to change here
Thanks again !!
You can check window.location.href. E.g.
if (window.location.href === 'http://my-URL/liste-boutique.php') {
new_shop.addEventListener('click', function(){
$("#shop_modal")[0].style.visibility = "visible";
});
}
Instead of checking the url, check if the element you want to find is on the page:
var $new_shop = $("#new_shop");
if ($new_shop.length > 0) {
var new_shop = $new_shop[0];
new_shop.addEventListener('click', function(){
$("#shop_modal")[0].style.visibility = "visible";
})
}
(I've used $ prefix on $new_shop to show it's a jquery object just for clarity)
Or, using your code as-is:
var new_shop = $("#new_shop")[0];
if (new_shop != undefined) {
new_shop.addEventListener...
Alternatively, if you use jquery, you don't need to worry about it as it will automatically not apply if the element doesn't exist:
$("#new_shop").click(() => { $("#shop_modal)").fadeIn(); });
I have a Function (with help of other user of stackoverflow), but only the first if statement works, the second not. I want to take advantage of this code to get both: http and https followed or not by www
function formatURL() {
var url = document.getElementsByName("URL")[0];
var formattedURL = document.getElementsByName("formattedURL")[0];
url = url.value;
if (url.substr(0, 0) === "") // with our without www
{
formattedURL.value = "https://" + url;
return;
} else
{
formattedURL.value = "http://" + url;
return;
}
}
formattedURL.value = url;
}
You're running into this issue because url.substr(0,0) will always be an empty string "" for any string value of url (your if statement is always true).
Not sure what exactly you're trying to compare url.substr against because we don't have all the possible inputs you give to your <URL/> elements. Otherwise, I could have an actual fix for you.
I would like to get URL request variables from a link and pass them to a CFC component. I already have working code (jQuery, AJAX, CFC) that will handle everything, but I just need to grab #URL.whatever# from a particular link.
Within Coldfusion code I can easily do so with #URL.whatever# but have no idea how to get it from the client side. Also, does it matter if I have been using IIS URL rewrite? I am currently rewriting www.website.com/page.cfm?category=cat1 to www.website.com/page/cat1.
in both cases Coldfusion can access the request variable with #URL.category#, there is absolutely no difference. So how can I do this with JavaScript/jQuery, it shouldn't be complicated, right?
Well, we'll need more details to suggest how to get a reference to the link, but something like this should work:
HTML
<a id="mylink" href="www.website.com/page.cfm?category=cat1">Website.com</a>
JS
var href = document.getElementById( 'mylink' ).href;
This question proposes a method to get the variables, I find it slightly easier to understand than Blaise's regular expression. It also properly unencodes values from the URL Get Querystring with Dojo
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
var params = getUrlParams();
console.log(params.myParam);
Right, what you want to use is function to parse the window.location.href variable.
var URL_PARAM = getUrlVars()["category"];
Or, if the URL to your page was www.website.com/page.cfm?category=cat1&anotherparam=12345
var URL_PARAM1 = getUrlVars()["category"];
var URL_PARAM2 = getUrlVars()["anotherparam"];
I can't say for sure how it would operate with URL rewrites.
URLVars:
function getUrlVars() {
var vars = {};
var parts =window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[ decodeURIComponent(key)] = decodeURIComponent(value);
});
return vars;
}
I wrote an answer for this question: New background according to url, the code I posted in my answer was to check a URL for the presence of a particular string and, if it was there, change the background-image of a given element.
So! Me being me, I thought I'd try and avoid jQuery and go for a more traditional vanilla JavaScript approach with the following:
var images = {
'halloween' : '/images/newbackground.jpg',
'christmas' : '/images/xmasbackground.jpg'
};
var url = document.location.href,
elem = document.getElementById('elementThatYouWantToStyle');
for (var keyword in images){
if (images.hasOwnProperty(keyword) && url.indexOf(keyword) !== -1) {
elem.style.backgroundImage = images[keyword];
}
}
Source.
Which I then thought I'd convert to a functional approach, so it became this:
var images = {
'halloween': 'http://davidrhysthomas.co.uk/img/dexter.png',
'christmas': 'http://davidrhysthomas.co.uk/img/mandark.png'
};
function setBG(el, map, url) {
if (!el || !map) {
return false;
}
else {
var url = url || document.location.href,
el = el.nodeType == 1 ? el : document.getElementById(el);
for (var keyword in map) {
if (map.hasOwnProperty(keyword) && url.indexOf(keyword) !== -1) {
el.style.backgroundImage = encodeURIComponent(map[keyword]);
}
}
}
}
setBG('one', images, 'http://some.domain.com/with/halloween.jpg');
setBG(document.getElementById('two'), images, 'http://some.domain.com/with/christmas.jpg');
JS Fiddle demo.
Now, if I add a console.log() to the if assessment within the for...in loop it shows that we're getting into the loop, and the console suggests that I have an accurate reference to the DOM node, the images object, the URL (as passed into the function) and am getting the correct value from the object.
The following line, however, in which I attempt to set the el.style.backgroundImage property, does not work (this is true whether or not I wrap the map[keyword] in the encodeURIComponent() or not albeit I've linked only to the attempt in which I did. So: what's the obvious flaw in my logic? Why is el.style.backgroundImage not being set?
(Incidentally JS Lint, at JS Fiddle, seems happy with it (other than the redefinition of existing variables (url and el) done in order to have a fall-back/default).
You are declaring a local variable url with var url that already defined as an argument url and you also need to use the form url(http:/xxxx).
Change to this (removed var in front of url and added the url() around the url):
function setBG(el, map, url) {
if (!el || !map) {
return false;
}
else {
url = url || document.location.href;
el = el.nodeType == 1 ? el : document.getElementById(el);
for (var keyword in map) {
if (map.hasOwnProperty(keyword) && url.indexOf(keyword) !== -1) {
el.style.backgroundImage = 'url(' + map[keyword] + ')';
}
}
}
}
An URL is not a valid backgroundImage value unless you wrap it in a url().
el.style.backgroundImage = 'url(' + map[keyword] + ')';
Fiddle
Also, you should not encodeURIcomponent the whole URL, otherwise it will encode even the protocol's : and the /'s, resulting in a 404 as (due to the now lack of protocol) being interpreted as a relative URL:
GET http://fiddle.jshell.net/_display/http%3A%2F%2Fdavidrhysthomas.co.uk%2Fimg%2Fdexter.png 404 (Not Found)
Instead, to more safely encode a full URI you can use encodeURI:
el.style.backgroundImage = 'url("' + encodeURI(map[keyword]) + '")';
Fiddle
Note: MDN mentions that encodeURI may not work as expected in different browsers with GET requests, that is, URLs including query strings. I couldn't reproduce that problem though.
Also as noted by #jfriend00, the var keyword before url is unnecessary, as it already belongs to the function scope due to being declared as a formal parameter. Read more: JavaScript Scoping and Hoisting
I have a querystring which looks like this page3.html?redesigndata=value which it appears if its redirected from page1.html and page3.html?new=yes or no when redirected from page2.html. Here is the code I'm using to find out what the querystring is and do some functions on page3.html
var locurl = window.location.search;
if (locurl.substring(0, 13) === '?redesigndata') {
alert("redesign!");
} else if (locurl.substring(0, 4) === '?new') {
visit = locurl.substring(5);
alert("somthing!");
if (visit === 'yes') {
alert("first!");
} else if (visit === 'no') {
alert("again!");
}
}
but I don't get any alerts when I try this script and I cant find out what's wrong with it.
Try using this function
function getQueryString() {
var result = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
// ...
var myParam = getQueryString()["myParam"];
Check like this
if(getQueryString()["redesigndata"] != "")
There is nothing wrong with the code you posted. If the alerts never fire, it's because the conditions are never met. Once a query string is added to the URL that DOES match one of those you listed in your code, the alert does fire.
Also, beware you're (seemingly) creating global vars.
The script works on my box. Please put this script inside script tags