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
Related
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 am using pdf.js library in my application.
It has integrated really well except for when i am trying to download the document. Everytime i download a specific file it gets downloaded as document.pdf
I have quite a lot of files to download and this is creating a bit of confusion.
My code goes as below:
<iframe src="pdf_viewer/web/viewer.html?file=/docs/resumes/1b763820-e262-4f76-8502-8872a3cb52e8&filename=sample.pdf"></iframe>
my first parameter is the file id and the second parameter is the name with which the document should be downloaded as.
Below code is the one present in the pdf viewer viewer.js file
function getPDFFileNameFromURL(url) {
var defaultFilename = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'document.pdf';
console.log(url);
console.log(defaultFilename);
if (isDataSchema(url)) {
console.warn('getPDFFileNameFromURL: ' + 'ignoring "data:" URL for performance reasons.');
return defaultFilename;
}
var reURI = /^(?:(?:[^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
var splitURI = reURI.exec(url);
var suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.indexOf('%') !== -1) {
try {
suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
} catch (ex) {}
}
}
return suggestedFilename || defaultFilename;
}
From my understanding of the code, what i am doing regarding the input is right. Where could i be going wrong ?
i figured out the solution
<iframe src="pdf_viewer/web/viewer.html?file=/docs/resumes/1b763820-e262-4f76-8502-8872a3cb52e8?sample.pdf"></iframe>
This takes the input in the url, now i can extract filename from the url
I am using Tampermonkey to save time on frequent tasks. The goal is to get content of an element on www.example1.com, navigate to another page, and do stuff there. The starting page is www.example1.com as seen from match. This is the code I am using:
//#match http://example1.com
var item = document.getElementById("myId").textContent;
window.open("http://example2.com","_self");
setTimeOut(function(
//perform clicks on this page
){},3000);
None of the code after changing URLs ever gets executed. Why, and what is the workaround?
Allow the userscript on both urls and use GM_setValue/GM_getValue to organize the communication.
//#match http://example1.com
//#match http://example2.com
//#grant GM_getValue
//#grant GM_setValue
if (location.href.indexOf('http://example1.com') == 0) {
GM_setValue('id', Date.now() + '\n' + document.getElementById("myId").textContent);
window.open("http://example2.com","_self");
} else if (location.href.indexOf('http://example2.com') == 0) {
var ID = GM_getValue('id', '');
if (ID && Date.now() - ID.split('\n')[0] < 10*1000) {
ID = ID.split('\n')[1];
.............. use the ID
}
}
This is a simplified example. In the real code you may want to use location.host or location.origin or match location.href with regexp depending on what the real urls are.
To pass complex objects serialize them:
GM_setValue('test', JSON.stringify({a:1, b:2, c:"test"}));
try { var obj = JSON.parse(GM_getValue('test')); }
catch(e) { console.error(e) }
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 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 */
})();