I'd like some help changing this JavaScript onclick event to just load the data on page the page load...
Preferably not using the body on load tag...
So obviously I'd pre-set the var for term inside the script term rather than the existing on click event..
Hope that made sense.
<p><a id="keywordlink" href="?term=wombats">Get keywords for wombats</a></p>
<script type="text/javascript" src="keywords.js"></script>
<script type="text/javascript">
var x = document.getElementById('keywordlink');
if(x){
x.onclick = function(){
var term = this.href.split('=')[1];
this.innerHTML += ' (loading...)';
KEYWORDS.get(term,seed);
return false;
}
}
function seed(o){
var div = document.createElement('div');
var head = document.createElement('h2');
head.innerHTML = 'Keywords for '+o.term;
div.appendChild(head);
var p = document.createElement('p');
p.innerHTML = o.toplist;
div.appendChild(p);
var head = document.createElement('h3');
head.innerHTML = 'Details:';
div.appendChild(head);
var list = document.createElement('ol');
for(var i=0,j=o.keywords.length;i<j;i++){
var li = document.createElement('li');
li.innerHTML = o.keywords[i].term + '('+o.keywords[i].amount+')';
list.appendChild(li);
}
div.appendChild(list);
x.parentNode.replaceChild(div,x);
}
</script>
change this:
if(x){
x.onclick = function(){
var term = this.href.split('=')[1];
this.innerHTML += ' (loading...)';
KEYWORDS.get(term,seed);
return false;
}
}
to something like this:
function loadSomething(){
var term = x.href.split('=')[1];
x.innerHTML += ' (loading...)';
KEYWORDS.get(term,seed);
return false;
}
loadSomething();
you can leave it where it is, but for readability, put it below the seed function.
You should use something like onload or document.ready, but alternatively you can move the whole script file to the bottom of the page
Don't set the event handlers that way. Use addEventListener and (for IE) attachEvent.
Related
I am trying to make an extension that makes a button which then executes a function, however, because the extension executes a javascript file after the page loads. However, when I create the button I want to run a function. Is there a way I can store a function and variables that can be run and access later by the button?
var effect = [[1,100],[2,32], [5,3]];
var points = (function(){var adding = 0;for(var i = 0; i<effect.length;i++){adding+=effect[i][0];};return adding;})()
var score = (function(){var adding = 0;for(var i = 0; i<effect.length;i++){adding+=effect[i][1];};return adding;})()
var percentage=(score/points*100).toString()+"%";
this.effect = effect;
this.points = points;
this.score = score;
var percentage = points/score;
function list_effect(){
var effect_string = "";
for(var i = 0; i<effect.length;i++){
effect_string += ((points-effect[i][0])/score) - ((points)/score);
}
alert(effect_string);
}
if(percentage == 'NaN%'){
// alert('ERROR');
}else{
document.getElementsByClassName("agenda")[0].innerHTML = "<button type=\'button\' id=\'get_list\'>Get List</button>"+ document.getElementsByClassName("agenda")[0].innerHTML;
document.getElementsByClassName("agenda")[0].innerHTML += "<script>" + "this.effect=" + effect.toString() + ";\nthis.points=" + points.toString()+ ";\nthis.score=" + score.toString() +"document.getElementById(\"get_list\").addEventListener(\"onclick\", list_effect());" + "</script>"
}
I have tryied useing this. however that does not work
<script> won't run when added via innerHTML, you should add it using appendChild
normally you don't need to add a <script> element at all, just use createElement and attach the listeners directly
var button = document.createElement('button');
button.id = 'get_list';
button.onclick = function (e) {
// use your variables here directly
};
// clear the previous contents
document.querySelector('.agenda').textContent = '';
// add the button
document.querySelector('.agenda').appendChild(button);
I have such code:
var pageCount = 5; //for example, doesn't really matter
var paginationList = document.createElement("ul");
paginationList.className = "pagination";
for(var i = 1; i <= pageCount; i++){
var paginationNode = document.createElement("li");
var paginationLink = document.createElement("a");
paginationLink.innerHTML = i;
paginationLink.href = "#";
paginationLink.onclick = function(){ console.log("yay"); }; //removed loadProperties here
paginationNode.appendChild(paginationLink);
paginationList.appendChild(paginationNode);
}
divxml.innerHTML = "";
divxml.appendChild(paginationList);
//code replaced by this comment inserts a lot of content to divxml
//for this bug or something to work, you need next line
divxml.innerHTML += "<br>";
divxml.appendChild(paginationList);
As you can see, I'm doing pagination here. The problem is that first pagination buttons don't work, I can't see yay in console when I click on them, but the second and last ones do work (I see yay in console when I click on them). What's wrong, How do I fix that?
You will have to create two list elements and two sets of list item elements for this to work:
var pageCount = 5; //for example, doesn't really matter
var paginationList1 = document.createElement("ul");
var paginationList2 = document.createElement("ul");
paginationList1.className = paginationList2.className = "pagination";
for(var i = 1; i <= pageCount; i++){
paginationList1.appendChild(createPaginationLink(i));
paginationList2.appendChild(createPaginationLink(i));
}
document.body.appendChild(paginationList1);
document.body.appendChild(document.createElement("br"));
document.body.appendChild(paginationList2);
function createPaginationLink(text) {
var paginationNode = document.createElement("li");
var paginationLink = document.createElement("a");
paginationLink.innerText = text;
paginationLink.href = "#";
paginationLink.addEventListener("click", function(){ console.log("yay"); }); //removed loadProperties here
paginationNode.appendChild(paginationLink);
return paginationNode;
}
And as stated in the other answer, mutating innerHTML will cause your elements to be re-created without their event listeners, so instead create and append your <br/> element using createElement and appendChild.
Codepen
divxml.innerHTML += "<br>";
Reading from innerHTML converts the DOM into HTML. The HTML does not have the event handlers that were attached to the DOM.
Writing the HTML back to the innerHTML (after appending <br> to it) converts the HTML to DOM and overwrites the DOM that was there before.
You have now destroyed the event handlers.
Don't use innerHTML.
Is this possible? Or is there a way to tack on and ID to an existing div?
This is my code. I can't get the code to work using classes, but I found when I used getElementById and changed the div to an ID, that it did. But I have a ton of already posted stuff so it would take forever to go through all those posts and change it manually to an ID.
Can I incorperate JQuery in this and still have it work? I tried that with something I stumbled across but it didn't work so I removed it. I don't remember what it is now though. :S
<div id="imdb" class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnum = document.getElementsByClassName("imdb");
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnum + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
window.onload = imdbdiv();
</script>
Can anyone help. I cannot for the life of me figure this out.
JsFiddle
Your problem was, you were appending the collection returned by document.getElementsByClassName instead of looping through the elements in the collection. You can verify this by looking at the href property of the link in your jsFiddle. You must loop through the values, then access the data in their innerHTML property.
You can use document.querySelectorAll to get a list of all elements matching a certain CSS selector, in your case .imdb. This is more flexible, in case you want to select elements with more than one class. I've pasted the code from the updated jsFiddle below.
function imdbdiv() {
var imdbMain = "http://www.imdb.com/title/",
end = "/#overview-top",
imdbValueDivs = document.querySelectorAll('.imdb'),
length = imdbValueDivs.length,
// Iterator values
i,
newDiv,
newLink;
// Loop over all of your link value containers
for (i = 0; i < length; i++) {
// Create the container
newDiv = document.createElement('div');
// Create the new link
newLink = document.createElement('a');
newLink.href = imdbMain + imdbValueDivs[i].innerHTML + end;
newLink.innerHTML = "My favorite film";
// Add the link to the container,
// and add the container to the body
newDiv.appendChild(newLink);
document.body.appendChild(newDiv);
}
}
window.onload = imdbdiv();
If you have many such divs on your page, then it could be like this:
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnums = document.getElementsByClassName("imdb");
for (var i =0; i < idnums.length; i++) {
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnums[i].innerText + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
}
window.onload = imdbdiv();
</script>
See jsfiddle
UPDATE:
The following string was incorrect:
window.onload = imdbdiv;
Okay, so your question is a little bit unclear.
The way I understood your question is that you have a whole bunch of div elements with class attribute and what you want is to simply copy the class value to the id attribute of the div elements.
If that's correct then try something like this with jquery:
<script>
$(document).ready(function(){
$(".imdb").each(function(imdbDiv){
var classValue = imdbDiv.attr("class");
imdbDiv.attr("id", classValue);
});
});
</script>
I have a code.js file which contains the following:
DivDialogHTML = function(){
var mainDiv = document.createElement("div");
mainDiv.id = "optin_settings_dialog";
mainDiv.className = "OptinDialog";
mainDiv.innerHTML = "<div>Text</div>";
}
The code to load the popup (dont know if it's all code, but to get the idea):
DivDialogOverlayHTML = function(){
var mainDiv = document.createElement("div");
mainDiv.id = "optin_settings_overlay_dialog";
mainDiv.className = "OptinDialog";
return mainDiv;
}
renderOptinWindow = function(){
var pageHead = document.getElementsByTagName("head")[0];
var pageBody = document.getElementsByTagName("body")[0];
if( pageHead && pageBody ){
pageBody.appendChild( this.getDivDialogHTML() );
}
}
Instead of using the mainDiv.innerHTML = '<div>Text</div>' I'd like the mainDiv.innerHTML to open another file (Dialog.html).
How do I do that?
with Ajax. But why not using jQuery?
$('.selector').load(url);
In your case you have to insert jQuery first like this in your
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
And than take your existing function and change it like this
DivDialogHTML = function(){
var $mainDiv = jQuery("div");
$mainDiv.attr('id', "optin_settings_dialog");
$mainDiv.addClass("OptinDialog");
/* $mainDiv.html("<div>Text</div>"); */
$mainDiv.load('Dialog.html');
}
Do you mean another window? If so, please take a look at window.open
window.open
After you create new window, you put its contents and display
if you don't want to use jQuery you can use an iframe
HTML
<iframe id="optin_settings_dialog"></iframe>
Javascript
document.getElementById("optin_settings_dialog").src="Dialog.html";
<!DOCTYPE html>
<html><body>
<p id="intro">Hello <em id="abcd">intro</em> World!</p>
<script type="text/javascript">
var txt=document.getElementById("intro").innerHTML;
var el = document.createElement("span");
el.innerHTML = txt;
var aa = el.getElementById("abcd").innerHTML;
alert( aa );
</script>
</body></html>
The above is a simple snippet. Actually I have an HTML editor and when the user saves the data I should save only the required content. Here I am getting the content of an element and manipulating it with DOM and pass the details to the server. This way I will not change the page content (user view remains the same) and he/she will continue editing the document.
The above is a simple example but in the real case I have to remove, change and move certain elements. The above code fails el.getElementById("abcd").innerHTML. Appreciate any pointers.
You can create a hidden iframe to manipulate all your changes, thus creating a separate DOM, then simply pull back the results you want.
var iframe;
if (document.createElement && (iframe = document.createElement('iframe'))) {
iframe.name = iframe.id = "externalDocument";
iframe.className = "hidden";
document.body.appendChild(iframe);
var externalDocument;
if (iframe.contentDocument) {
externalDocument = iframe.contentDocument;
} else if (iframe.contentWindow) {
externalDocument = iframe.contentWindow.document;
}
else if (window.frames[iframe.name]) {
externalDocument = window.frames[iframe.name].document;
}
if (externalDocument) {
externalDocument.open();
externalDocument.write('<html><body><\/body><\/html>');
externalDocument.close();
/* Run your manipulations here */
var txt = document.getElementById("intro").innerHTML;
var el = document.createElement("span");
el.innerHTML = txt;
/* Attach your objects to the externalDocument */
externalDocument.body.appendChild(el);
/* Reference the externalDocument to manipulate */
var aa = externalDocument.getElementById("abcd").innerHTML;
alert(aa);
}
/* Completed manipulation - Remove iFrame */
document.removeChild(iframe);
}
I have it working here:
http://jsfiddle.net/ucpvP/
Try using jQuery like given below.
function SaveData() //Your add function
{
var txt=$("#intro").html();
$(document).append("<span id='abcd'>" + txt+ "</span>");
var aa = $("#abcd").hmtl();
alert(aa);
}
You can use a DOM Element that is never appended to the DOM.
I use this 'cleanup' function:
function cleanup(str){
var tester = document.createElement('div'),
invalid, result;
tester.innerHTML = str;
//elements I don't allow
invalid = tester.querySelectorAll('script,object,iframe,style,hr,canvas');
// the cleanup (remove unwanted elements)
for (var i=0;i<invalid.length;(i+=1)){
invalid[i].parentNode.removeChild(invalid[i]);
}
result = tester.innerHTML;
tester = invalid = null;
//diacritics to html-encoded
return result.replace(/[\u0080-\u024F]/g,
function(a) {return '&#'+a.charCodeAt(0)+';';}
)
.replace(/%/g,'%25');
}
//usage:
cleanup(document.getElementById("intro").innerHTML);
You can extend the function with your own code to remove, change and move certain elements.