Exists any JavaScript or Objective-C method to convert a location.href="MyURL" to ??
I have over 200 location.href URL not working with UIWebViewNavigationTypeLinkClicked :-S
Thanks to everyone can help me!
<script type="text/javascript">
document.getElementById("myAnchor").setAttribute("href", window.location.href);
var loc = document.getElementById("myAnchor").getAttribute("href");
var t = document.createTextNode(loc);
document.getElementById("myAnchor").appendChild(t);
</script>
Here is one way of doing it: document.getElementById() grabs a reference to the ID attribute of your anchor(s). The second argument of setAttribute(), "window.location.href" grabs a reference to the url in the current window and sets the href attibute in your anchor to this, however if you have a bunch of location.href()s declared in your code, then store these as a variable before the first line instead and then reference that variable at around the same line as where I have declared "loc". The variable "loc" declares a variable which stores a reference to the newly created href attribute you just declared in the previous line. Then I am declaring a variable "t" which creates a text node in the DOM, with the href from the previous line as the value this variable will hold. Lastly, I use document.getElementById to get "myAnchor" again and append the text node from the previous line to it. So now we can actually see the url in the link.
//Also, use a for loop to run this action 200 times and correct all of the hrefs on your page.
<script type="text/javascript">
for (var i=0;i<200;i++){
//run document.getElementById() and .setAttribute, .createTextNode, etc. here
}
</script>
Working fiddle: http://jsfiddle.net/1so33q4z/36/
I would not recommend using document.write(); as mentioned in the other person's post, as this causes the page to work in a way the DOM is not meant to (writes serialized text). Especially if you need to correct 200 of them. See this post Why is document.write considered a "bad practice"?
Related
This is probably a really silly question, but I can't find it online anywhere and I've been looking for at least an hour.
I have a link Instruments which I want to get the ID of it once clicked, as I need to pass some variable to the page I am opening to know that the instruments link was clicked. This is being called from productInformation.html
I have also tried doing Instruments and then in my JavaScript, window.open("MusicMe.html", "_self"); and then tried passing a variable that way, but still absolutely no luck. Any help as to how I would pass a variable back to the page when it opens would be brilliant.
Once it opens, I am using the variable to set the ID of an element so it only displays a certain set of the information, which is working on it's own, but when I go back to try and call it, it's always thinking it is showing them all as I cannot work out how to set the variable to define it. Unfortunately I need to use JavaScript not PHP.
Thanks.
I would just tell you some ways, hope you would be able to implement it:
Use query params to pass the variable.
When you're navigating to another page, add query params to the url.
window.open("MusicMe.html?variable=value", "_self");
In your next page, check for queryParam by getting window.location.href and using regex to split the params after ? and get that data.
Use localStorage/cookies
Before navigating to the next page, set a variable in your localStorage
localStorage.setItem("variable","value");
window.open("MusicMe.html", "_self");
In your second page, in the window load event.
$(function() {
if(localStorage.getItem("variable")) {
// set the ID here
// after setting remember to remove it, if it's not required
localStorage.removeItem("variable");
}
});
You can use localStorage to keep the value, or use parameter like
href="MusicMe.html?id=111"
to pass the value to new page.
You can always pass a GET variable in you re URL just like this myhost.com?var=value
You can get the value of this variable by parsing the URL using Js see this
How can I get query string values in JavaScript?
You can simply pass # value into url, get it and then match it with 'rel' attribute given on specified element.
Here I have done materialize collapsible open from link on another page.
JS:
var locationHash = window.location.hash;
var hashSplit = locationHash.split('#');
var currentTab = hashSplit[1];
$('.collapsible > li').each(function() {
var allRels = $(this).attr('rel');
if(currentTab == allRels){
$(this).find('.collapsible-header').addClass('active');
$(this).attr('id',currentTab);
}
});
I've been struggling to convert a JavaScript function to a global variable.
I've got 2 files in total that are basically part of the entire function, here is the JavaScript function.
<script type="text/javascript">
$.get("banner1.php", function(getbannerlink1) {
$("#banner1").load(getbannerlink1+ " #productImage");
// var window.bannerlink1=getbannerlink1; (this doesn't want to work)
});
<script>
Basically banner1.php selects ONE random URL out of an array, and echoes the URL. This JavaScript then gets the URL, and then does a .load() function of that URL and gets the #productImage class from that URL, basically it gets the product image from the random URL. That works all good. Now I need to convert the getbannerlink1 variable to a global variable, because I would like to use the link outside of this function as well.
I've tried using the following just before closing the function:
var window.bannerlink1=getbannerlink1;
but this is just destroying the function altogether :/
What am I doing wrong?
var window.bannerlink1 is a syntax error. var should only be used with variable identifiers, which may not contain a period.
You want to set a property of window, not declare a new variable name, so just drop the var.
Drop the var
window.bannerlink1 = getbannerlink1;
Ideally you would avoid using a lot of globals and use a global namespace to hold the values.
I am looking at someone elses codebase and I as a javascript noob and doubly so a regular expression noob I can't figure out what the following lines do:
var url = sel.anchorNode.parentNode.href;
var match = self.location.href.replace(/\/$/i, '');
var replaced = url.replace(match,'');
I read it as:
set the var url to the href value of the parent node of the currently selected node
sets the var match to the browsers current URL with the trailing '/' removed (if it exists)
sets the var replaced to the string returned in 1. with the string returned in 2. removed from it
If I am reading it correctly I just can't figure out how it would ever do anything. There isn't any situation, I can think of, where the parent node of a currently selected node would have an href value pointing to the current URL.
So I think I am reading it incorrectly.
Because the href property of an anchor is a fully-resolved URL (even if the href attribute is relative), what that does is remove the current page's path and get you back to a relative URL. E.g., on the page:
http://example.com/foo/bar/
with a link like
...
...you get the href from the anchor which is:
http://example.com/foo/bar/nifty.html
...and then remove http://example.com/foo/bar from it, giving you:
/nifty.html
In this case, of course, that's probably not what you actually want. :-) I have to admit I fail to see how the code is useful, out of context, but then context is king sometimes...
I am trying to add a character counter to a page, on this page i enter in three values and it returns a large string in the innerHTML of a div with the ID of 'AnswerBoxID', now i want my script to obviously count the number of characters in it to do this i have written
var submit=document.getElementsByClassName('Row3');
function countChars(){
count = document.getElementById('AnswerBoxID').innerHTML.length;
document.title ="Chars "+count+"/160";
}
Which returns a ROUGH approximate of the chars, when i then paste it into an editor or something else that counts chars i get a different result again, counting with this method gets within 5 chars of what other things are reporting (specifically notepad++).
BUT my biggest problem is I have been unable to get countChars() to update
when the value of document.getElementById('AnswerBoxID').innerHTML updates, in javascript I overcame that using the following code
var submit=document.getElementsByClassName('Row3');
for (i=0; i<submit.length; i++){
submit[i].firstChild.setAttribute('onclick','countChars()');
}
After reading GM Pitfalls 2 i then modified my approach to the following
for (i=0; i<submit.length; i++){
submit[i].firstChild.addEventListener('click',countChars(),true);
}
But it still doesnt work!
And before anyone asks yes I do define the count variable before the function. I don't really mind the mostly accurate length thing I would prefer it to be more precise but I do really want to add onclick elements that run countChars() to the submit buttons.
You seem to add the event handler wrong.
elm.setAttribute('onclick','countChars()');
would set an attribute, and eval 'countChars()' in the global scope when the element is clicked. Yet, Greasemonkey scripts run sandboxed to their own global object, and your declared function "countChars" is not available to the eval.
elm.addEventListener('click',countChars(),true);
executes the function immediately and adds the return value as a handler. To make it work, just remove the brackets and pass the function itself. See also element.addEventListener
Greasemonkey scripts run sandboxed. That means, the script runs in the page's onload event then is removed. Calling your Greasemonkey script's countChars() function when the form is submitted will return an undefined error, as your function object is no longer present in the DOM.
Here's my simplified contentEval function (based on GM wiki's Content Script Injection's function):
function contentEval(source) {
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.textContent = source;
document.head.appendChild(script);
}
You can also set the text property instead of textContent for compatibility with older IE versions, thanks RogG!
Put that function in your GM script, it will serve to append any function you need to user later to the DOM's head.
Pass your countChars function as a parameter to the contentEval function:
contentEval(function countChars() {
var count = document.getElementById('AnswerBoxID').textContent.length;
document.title ='Chars '+count+'/160';
});
This way, your countChars function will be placed inside a script element appended to the document's head, which will be accessible after the GM script's execution time ends.
If you want to check a demo of the code above, use a DOM Inspector in this fiddle. It creates a new script element which is appended to the (in JSfiddle's case, the iframe's) document's head, meaning it will be accessible whenever you need it.
You could also simply attach the function to the unsafeWindow, but you should avoid using unsafeWindow unless strictly necessary, and note that unsafeWindow is not supported in Google Chrome.
Use this page for reference: http://wiki.greasespot.net/Content_Script_Injection
Also use the .textContent method to get the text content of an element (and its descendants) as noted by RobG.
In GreaseMonkey, you should be able to use:
var count = document.getElementById('AnswerBoxID').textContent.length;
I've been here and accordingly found out that this piece of code here
var node_exists=$(treeselector).find("li[id^='someid']");
where treeselector is the selector to the element within which the elements to be searched for are contained.This works perfectly fine.
However when in the id^='someid' part I try to change 'someid' to some variable which contains the id then it stops working.
var someid='someid'
var node_exists=$(treeselector).find("li[id^=someid]");
I also tried concatenating single quotes when the parameter is recieved in the function where this is fired.
I think this might have to do with the double quotes surrounding the li[id^='someid'] part. Any idea as to how to make this work?
Cheers !!
Concatenate:
var someVar = 'id1';
var node_exists=$(treeselector).find("li[id^="+someVar+"]");