I'm trying to get this conditional statement to work, but having no luck
<body onload="HashTagInsert()">
function HashTagInsert() {
var hash="window.location";
if (hash==="http://www.address.com#anchor1")
{
document.getElementById("insert-text").innerHTML="<h2>Title</h2><p>body text</p>";
}
else if (hash==="http://www.url.com/foler/code/page.html#anchor2")
{
document.getElementById("insert-text").innerHTML="<h2>Title</h2><p>body text</p>";
}
else ()
{
document.getElementById("insert-text").innerHTML="something else text"
}
}
</body>
If you want the hash variable to be the value of the window.location object, then don't put quotes around the object name as that will turn it into a string literal.
var hash = window.location;
I recommend not calling the variable hash though, as that could be confused with window.location.hash, which contains the fragment ID component of the URL.
Don't add quotes around window.location.
var hash = window.location.href;
If you want to compare your current window location with some string you need to set the "hash" variable correctly:
var hash = window.location;
but I am not sure if I got your problem.
In case that your javascript can not set your html properly, there is also a timing problem. It depends when your javascript gets called. Before or after your DOM has been rendered. Because if your javascript is executed before your DOM (and your element '#insert-text') is rendered, you wont be able to select this DOM element.
And ... but this is perhaps just my opinion, is is pretty uncool to have masses of if / else if / else constructions in your code.
You might want to map some url and text so that you do not need to make your life harder than it is.
for example:
var html;
var mapping = {
"http://www.address.com#anchor1":"<h2>Yeah</h2><p>Baby</p>",
"http://www.address.com#anchor2":"<h2>Cool</h2><p>Tomato</p>",
"default": "<h2>Woops</h2><p>Honolulu rocks</p>"
}
mapping[window.location.href] ? html = mapping[window.location.href] : html = mapping['default'];
document.getElementById("insert-text").innerHTML=html;
Related
Our client has two URL's that point to the same page. Depending on which URL the user comes through they want to display and hide certain content. I have the following code and everything looks like it should work (doesn't it always....) but for some reason the if doesn't evaluate to true. The alert is in there for troubleshooting purposes.
var this_page = window.location;
var calc_address = "DIFFERENT ADDRESS";
alert(this_page);
if(this_page == "http://www.calculatesnowguards.com/"){
$('#mashead').css('background-image', 'url("../images/masthead_bg.jpg") ');
$('.calc_remove').hide();
$('#bottom').innerHTML = calc_address;
}
window.location is not a string, it's only represented as so. It's actually an object. window.location.href is the variable you want to compare to.
EDIT: (In response to the comments below.) With such different URLs, why would you try to compare them directly?
if (window.location.href.indexOf("calculatesnowguards.com") >= 0) {
//code for calculatesnowguards.com
} else{
//code for snowguards.biz
}
EDIT2: Sorry, didn't realize that contains() was a Firefox only function. I extend String to include it in my scripts.
Bit of a javascript newbie so not sure if this question is easy or impossible.
Am working on a site with different testing environments and have made a greasemonkey script to make a set of buttons to switch from one to another:
if (/^(.*?)\www.mysite.com(.*)$/.test(document.location.href)) {
document.location.href = RegExp.$1+"iww1.mysite.com"+RegExp.$2
}
This has been working except for some URLs have a search string ID that also needs changing to a different number too.
&storeId=15162
I feel like I've exhausted my limited knowledge, by adding another if function within the {} to adding various replace functions, all to no avail.
If this makes sense and anyone can help it would be much appreciated.
Cheers
Your first problem is that the location object is magical: assigning to it, or to any of its properties, causes the browser to navigate to the assigned URL. Since this will typically stop your script, you won't be able to do it twice. Instead, you should store the intermediate URL in some other variable, and only assign it back to location.href once you're ready to move to the new page.
Also, you didn't specify how the new "search string ID" should be calculated, so I just assumed that you have some function, named e.g. getNewStoreID(), that will return the new ID when you give it the old one. Given such a function, this code should do it:
var siteRegExp = /www\.mysite\.com/;
var paramRegExp = /([?&]storeId)=(\d+)/;
if ( siteRegExp.test( location.href ) ) {
var href = location.href.replace( siteRegExp, "iww1.mysite.com" );
var match = paramRegExp.exec( href );
if ( match ) {
href = href.replace( paramRegExp, "$1=" + getNewStoreID( match[2] ) );
}
location.href = href; // navigate to the new URL!
}
Suppose I have a web page
http://foo.com/bar.html
Is there any way I can provide a link to that page that, for sake of example, makes all <b> sections red?
I'm guessing I need some script in bar.html and a URL something like
http://foo.com/bar.html?style="b{color:red;}"
Is this possible and if so, is there a standard way to do it?
You can read the query string via location.search and then apply whatever logic you want to the string you get back.
Be careful not to open yourself up to an XSS attack.
why don't you try it with CSS?
inside example.css file:
br
{
color:red;
}
I would say the easiest and most abstract way would just be to append the style directly to the head. Again though, as stated, you may want to parse it and verify its proper format and avoid attacks. You'd be giving every web user direct access to your stylesheet in your head.
window.onload = function() {
if(document.location.search.indexOf('style=')>-1) {
var style = decodeURI(document.location.search.substring(document.location.search.indexOf('style=') + 6));
if(style.indexOf(',')>-1) { style = style.substring(0,style.indexOf(',')); }
var elem = document.createElement('style');
elem.type='text/css';
elem.innerHTML = style;
document.head.appendChild(elem);
}
};
Then you could add any and all style modifications to your URI like this ?style=body{background-color:blue;}%20b{color:red;}
You can customize javascript to do whatever you want. There's no pre-existing, universal way of doing this.
You could check document.location.hash to pull out a value and add a new style for b elements. Query-string parsing is a bit more difficult as it's not built into JS by default.
You could add a handler to a link element.
You can do it like this:
document.getElementById('clickme').onclick = function(){
var bolds = document.body.getElementsByTagName("b");
for(var i = 0; i < bolds.length; i++){
bolds[i].style.backgroundColor = 'red';
}
}
Demo: http://jsfiddle.net/maniator/HH2Cv/
I am customizing Denis Gritcyuk's Popup date picker.
This pop-up script uses inline Javascript in a href link, to set the selected date into the input field, in the parent window, that is was called for. An example URL looks like:
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.close();">3</a>
The input field name, (e.g. document.formname.field), is passed to the script as a string parameter.
I would like to add things done when that link is clicked (e.g. change background color of field, set flag, etc.). So while this DOES work, it's getting ugly fast.
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.opener.document.formname.field.style.backgroundColor='#FFB6C1';
window.close();">3</a>
How would I move these inline commands into a JS function? This would give me much cleaner URLs and code. The URL would now look something like
3
with a function like (this example obviously does NOT work):
function updateField (str_target, str_datetime) {
var fieldName = "window.opener" + str_target;
[fieldName].value = str_datetime;
[fieldName].style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
So any suggestions on how this can be done, please?
I'd prefer to hide the dom path tracing back from the current window back to the opener. It's appropriate to bake that into the function since the function will always be used in the context of that child popup. Then your function call is cleaner and more readable. Obviously, replace "myField" with the ID of the field you're intending to update.
3
function updateField ( str_date, str_fieldname ) {
var fieldToUpdate = document.getElementById( str_fieldname );
fieldToUpdate.value = str_date;
fieldToUpdate.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
You're acessing the property incorrectly. Try:
function updateField (str_target, str_datetime) {
var fieldName = window.opener;
str_target = str_target.split('.');
for (var i = 0; i < str_target.length; i++)
fieldName = fieldName[str_target[i]];
fieldName.value = str_datetime;
fieldName.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
The bracket notation ([]) is only used for properties of objects, not objects themselves. If you found my post helpful, please vote for it.
You can build a string and evaluate it as code using the eval function, but I would recommend against it.
There are a couple of things wrong with your code:
You cannot use the [] operator in a global context, you have to suffix it on an object, so you can say window["opener"] and this will be equivalent to window.opener, but there is no such thing as simply ["window"]
When navigating nested properties, as in window.opener.document you cannot navigate multiple levels using the [] operator. I.e. window["opener.document"] is not allowed. You must use window["opener"]["document"] instead.
how can I append variables to an URL with javascript without navigating to the url ?
thanks
To append variables to the hash (as Matthew suggested), you can do the following in plain JavaScript:
window.location.hash = 'varA=some_value;varB=some_value';
This will add #varA=some_value;varB=some_value to your URL. It will not refresh the page unless the hash value is equal to an anchor name or an element id within the document.
Then to check if a hash value is present, simply do the following:
var i, variables = window.location.hash.split(';');
if (variables.length > 0) {
// Variables present in hash
for (i = 0; i < variables.length; i++) {
keyValuePair = variables.split('=');
// keyValuePair[0] would be the key (variable name)
// keyValuePair[1] would be the value
}
}
else {
// No variables in the hash
}
You may also want to check out the following Stack Overflow post on issues related to the URL encoding of the hash part in different browsers:
Encoding of window.location.hash
You can modify window.location.hash. Anything else will cause a navigation.
I am not sure about that, but how is it with this?:
document.url + myVar + 'myString';
Though Javascript is not my language :P