Lowyat.NET Forums

Welcome Guest ( Log In | Register )

LYN wins Intel-Lenovo-Tangs Blogathon challenge. Thank you everybody!
 
RSS feedBump TopicReply to this topicStart new topicStart Poll

Outline · [ Standard ] · Linear+

> Insert new element using javascript

mumeichan
post Nov 5 2009, 01:21 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #1


Individual
******

Group: Senior Member
Posts: 1,898
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: May 2005





I am writing a Greasemoneky script and I want to insert some form elements after the <body>blablabla<body> part of the page.

What is the general way of inserting new elements using javascript or jQuery with Greasemonkey?

I've read a book on Javascript and also follow some examples online but it doesn't seem to be working too well.

This is the code I used to create a new button

CODE
// ==UserScript==
// @name          NewButton
// @namespace     None
// @description   Newbutton
// @include       http://www.epicmafia.com/game/index/*
// @require       http://code.jquery.com/jquery-latest.min.js
// ==/UserScript==

window.onload = function createButton() {

   var myButton = document.createElement('input');

   var id = document.createAttribute('id');
   var type = document.createAttribute('value');

   myButton.setAttribute('id', 'submit');
   myButton.setAttribute('value', 'Submit');

   document.appendChild(myButton);
}

User is online!Profile CardPM
Go to the top of the page
+Quote Post
sunsuron
post Nov 5 2009, 01:48 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #2


PHP Web Developer
*****

Group: Senior Member
Posts: 750
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: Nov 2004






» Click to show Spoiler - click again to hide... «
User is offlineProfile CardPM
Go to the top of the page
+Quote Post
mumeichan
post Nov 5 2009, 06:34 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #3


Individual
******

Group: Senior Member
Posts: 1,898
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: May 2005





Thanks. But I tried your code, it does not work.
User is online!Profile CardPM
Go to the top of the page
+Quote Post
sunsuron
post Nov 5 2009, 07:38 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #4


PHP Web Developer
*****

Group: Senior Member
Posts: 750
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: Nov 2004






This is GM issue. Remove the window.onload line and replace with the function invoke.

» Click to show Spoiler - click again to hide... «
User is offlineProfile CardPM
Go to the top of the page
+Quote Post
mumeichan
post Nov 5 2009, 09:51 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #5


Individual
******

Group: Senior Member
Posts: 1,898
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: May 2005





QUOTE(sunsuron @ Nov 5 2009, 07:38 PM)
This is GM issue. Remove the window.onload line and replace with the function invoke.

» Click to show Spoiler - click again to hide... «

*



Thanks. You've helped so much, I wouldn't have learned so much so fast without you.

Now the code work. So GM can't support events? Is there a documentation or collection somewhere about all the problems with GM?
User is online!Profile CardPM
Go to the top of the page
+Quote Post
hkk86
post Nov 6 2009, 02:28 AM
Show posts by this member only |This post's rating (0+, 0-) | Post #6


Getting Started
**

Group: Junior Member
Posts: 75
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: Jul 2007





the documentation u want is probably the FAQ or the bug reports
or simply the best invention to let people collectively edit and contribute knowledge aka the wiki
http://wiki.greasespot.net/
User is offlineProfile CardPM
Go to the top of the page
+Quote Post
mumeichan
post Nov 6 2009, 12:48 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #7


Individual
******

Group: Senior Member
Posts: 1,898
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: May 2005





Omg I am getting so frustrated with this thing. Ok So I used the code that sunsuron gave and the button appears at the bottom of the page as I want it to. Now I try to add the new line
"myButton.onclick = 'window.alert('Hi')';"
and then the no button shows up. The new code looks like this:
CODE
function createButton() {

var myButton = document.createElement('input');
myButton.type = 'submit';
myButton.id = 'myid';
myButton.value = 'Click Me';
myButton.onclick = 'window.alert('Hi');';

document.body.appendChild(myButton);
}

createButton();


Please help by pointing out where I went wrong.

Also how do I insert a whole chuck of html at once. Say I have designed alot og things using dreamweaver and I want to paste the whole chunk of HTML into the page. Can I use this below
CODE
function createHtml() {

var newPara = document.createElement('p');
newPara.id = 'myid';
newPara.innerHTML = 'all the html here';


document.body.appendChild(newPara);
}

createHtml();


Or do I use this. I tried this out and it work, but I wonder what happens if I have a lot of html line. Is there a better or neater way to insert it.
CODE
function createPara() {
   $('<p>all the html here</p>').appendTo('body');
};

createPara();


Does GM have a problem with the onclick event or something?
Why when I put in this code, the button appears
CODE
function createPara() {
   $('<p><form><input name="" type="submit" onClick="fff" value="Click Me" /></form></p>').appendTo('body');
};

createPara();

But when I use this code, nothing appears? I changed "fff" to "window.alert('Hi');"
CODE
function createPara() {
   $('<p><form><input name="" type="submit" onClick="window.alert('Hi');" value="Click Me" /></form></p>').appendTo('body');
};

createPara();

I've read a few sites on common mistakes when coding for GM and I wrote this up but it still doesn't work
CODE
unction createPara() {
   $('<p><input name="" id="button1" type="button" value="Click Me" /></p>').appendTo('body');
};

function sayHi() { alert('Hi'); };

funtion theEvent() {
   var elmLink = document.getElementById('button1');
   elmLink.addEventListener("click", sayHi, true);
};

createPara();
theEvent();


This post has been edited by mumeichan: Nov 6 2009, 07:38 PM
User is online!Profile CardPM
Go to the top of the page
+Quote Post
sunsuron
post Nov 7 2009, 04:51 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #8


PHP Web Developer
*****

Group: Senior Member
Posts: 750
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: Nov 2004






Tested this one and it's working on FF 3.5.5
CODE

function createButton() {

 var myButton = document.createElement('input');
 myButton.type = 'submit';
 myButton.id = 'myid';
 myButton.value = 'Submit';
 myButton.addEventListener('click', function() {alert('test')}, false);
 document.body.appendChild(myButton);
}

createButton();
User is offlineProfile CardPM
Go to the top of the page
+Quote Post
mumeichan
post Nov 7 2009, 06:50 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #9


Individual
******

Group: Senior Member
Posts: 1,898
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: May 2005





QUOTE(sunsuron @ Nov 7 2009, 04:51 PM)
Tested this one and it's working on FF 3.5.5
CODE

function createButton() {

 var myButton = document.createElement('input');
 myButton.type = 'submit';
 myButton.id = 'myid';
 myButton.value = 'Submit';
 myButton.addEventListener('click', function() {alert('test')}, false);
 document.body.appendChild(myButton);
}

createButton();

*



Thanks. It seem after every solution I encounter yet another problem. I created a GM user script using the code you wrote to get usernames and added this button code to it. So I modified the addEventListener line to this
CODE
myButton.addEventListener('click', function() { alert(my_paragraphs) } , false)


my_paragraphs is a variable already defined earlier in the user script. What happens is the button shows up but when click a blank alert box appears. I read some forums and the GM wiki and I understand it's something to do with the function trying to call a value which is not actually in the page but the the GM sandbox. I don;t really understand how to solve that problem. I think I have to 'write' the function only the page first and then only call it using the event handler, though I am not sure. Please help, yet again.... sweat.gif cry.gif
User is online!Profile CardPM
Go to the top of the page
+Quote Post
sunsuron
post Nov 7 2009, 07:05 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #10


PHP Web Developer
*****

Group: Senior Member
Posts: 750
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: Nov 2004






You can do all your 'processing' inside the anonymous function like this:

CODE

(function() {

 var myButton = document.createElement('input');
 myButton.type = 'submit';
 myButton.id = 'myid';
 myButton.value = 'Submit';
 myButton.addEventListener('click', function() {
   
   var usernames = []; // will store array of username
   var spans = document.getElementsByTagName('span'); // get all <span> in this page
   for (var i in spans) { // loop every <span>
       if (spans[i].className == 'normalname') { // check if the class is 'normalname'
           var a = spans[i].getElementsByTagName('a')[0]; // get the first <a> inside <span>
           usernames.push(a.text); // get the text property of the <a> which is the username
       }
   }
   
   alert(usernames); // echo all usernames in this page including duplicates
   
 }, false);
 document.body.appendChild(myButton);
})();
User is offlineProfile CardPM
Go to the top of the page
+Quote Post
mumeichan
post Nov 8 2009, 01:11 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #11


Individual
******

Group: Senior Member
Posts: 1,898
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: May 2005





QUOTE(sunsuron @ Nov 7 2009, 07:05 PM)
You can do all your 'processing' inside the anonymous function like this:
» Click to show Spoiler - click again to hide... «

*



Thanks again. Now as expected I've encountered another problem. I am trying to use the array to populate a listbox. So this is a code I added
CODE

var newListBox = $('<select name="userNameList" id="userNameList"><option value="">UserName</option></select>').appendTo('body');

(function() {

 var myButton = document.createElement('input');
 myButton.type = 'submit';
 myButton.id = 'myid';
 myButton.value = 'Submit';
 myButton.addEventListener('click', function() {
   
   var usernames = []; // will store array of username
   var spans = document.getElementsByTagName('span'); // get all <span> in this page
   for (var i in spans) { // loop every <span>
       if (spans[i].className == 'normalname') { // check if the class is 'normalname'
           var a = spans[i].getElementsByTagName('a')[0]; // get the first <a> inside <span>
           usernames.push(a.text); // get the text property of the <a> which is the username
       }
   }
   
   function addOption(selectbox, text, value) {
           var optn = document.createElement("OPTION");
           optn.text = text;
           optn.value = value;
           selectbox.options.add(optn);
       };

       for (var i = 0; i < usernames.length; ++i) {

           addOption(newListBox , my_paragraphs[i], my_paragraphs[i]);
       };

   
 }, false);
 document.body.appendChild(myButton);
})();


Hmm So where did I go wrong? The listbox and the button appears. But nothing happens when I click the button.

This post has been edited by mumeichan: Nov 8 2009, 01:13 PM
User is online!Profile CardPM
Go to the top of the page
+Quote Post
sunsuron
post Nov 8 2009, 01:46 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #12


PHP Web Developer
*****

Group: Senior Member
Posts: 750
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: Nov 2004






CODE
(function() {

  var myButton = document.createElement('input');
  var sel = document.createElement("select"); // new <select>
   
  myButton.type = 'submit';
  myButton.id = 'myid';
  myButton.value = 'Submit';
  myButton.addEventListener('click', function() {
   
    var usernames = [];
    var spans = document.getElementsByTagName('span');
    for (var i in spans) {
        if (spans[i].className == 'normalname') {
            var a = spans[i].getElementsByTagName('a')[0];
            usernames.push(a.text);
        }
    }
   
    for (var i in usernames) {
        var opt = document.createElement("option"); // new <option>
        opt.text = usernames[i];
        opt.value = usernames[i];
        sel.appendChild(opt);
    }
   
    document.body.appendChild(sel); // attach <select> before </body>
   
  }, false);
 
  document.body.appendChild(myButton);
})();


This post has been edited by sunsuron: Nov 8 2009, 01:51 PM
User is offlineProfile CardPM
Go to the top of the page
+Quote Post
mumeichan
post Nov 8 2009, 11:25 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #13


Individual
******

Group: Senior Member
Posts: 1,898
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: May 2005





Thanks again. Haha got another problem.

Please help me with another part too. I am trying to populate multiple select boxes using a single array of data when I click a button. However when I use the code below, only the last select box gets populated when I click the button.
CODE
for (var i in my_paragraphs) {
           var opt = document.createElement("option"); // new <option>
           opt.text = my_paragraphs[i];
           opt.value = my_paragraphs[i];
           nightAction.appendChild(opt);
           visit1.appendChild(opt);
           visit2.appendChild(open);
       }


So only the visit2 select box is populated while nightAction and Visit1 isn't.

I've realized another problem with GM. I can't use any of the methods you though me to select classes that contain hyphens. So I used back the two types of functions you gave me to select all the 'td' with the class of 'score-lt prt' .But it returns no result.

This post has been edited by mumeichan: Nov 9 2009, 06:27 PM
User is online!Profile CardPM
Go to the top of the page
+Quote Post
sunsuron
post Nov 10 2009, 01:32 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #14


PHP Web Developer
*****

Group: Senior Member
Posts: 750
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: Nov 2004






The code snippet you gave is not enough to know what went wrong.
User is offlineProfile CardPM
Go to the top of the page
+Quote Post
mumeichan
post Nov 11 2009, 02:07 PM
Show posts by this member only |This post's rating (0+, 0-) | Post #15


Individual
******

Group: Senior Member
Posts: 1,898
Ratings earned: 0+, 0-
Ratings given: 0+, 0-

Joined: May 2005





QUOTE(sunsuron @ Nov 10 2009, 01:32 PM)
The code snippet you gave is not enough to know what went wrong.
*



Thanks for taking a look. I figured out what when wrong already. Hmm I got another problem. I'm trying to create a special chat box. I want to choose two names from a list. Then when I type some text into a text box, I want it to add a line into the text box in such a way.

Name1: bla bla bla
Name2: bla bla bla
Name1: bla bla bla
Name2: bla bla bla

However the only one inputing the 'bla bla bla' is me and the code automatically alternate between Name1 and Name2 to add before the 'bla bla bla'.

So I will need two code. The first one is to add a line into the textarea. So far I only know how to set the value of the text area when I press enter. I can't find the method to add a line.

Second part is I need to know how to alternate between name1 and name2 and add it to the begining of the text I typed before adding it as a new line in the textarea.
----------------------

QUOTE
Also how do I remove a certain index from an array if that index contains a certain string? For example

var message = new Array('I love you', 'I hate you', 'Rose loves you')

for ( var i in message) {
           if ( message[i] contains 'Rose loves') {remove message[i] from the array};
};

Then now message = ('I love you', 'I hate you') cause 'Rose loves you' has been removed.

Thanks!


I solved it already using a backward loop, condition statement, regular expression and splice. Man this is making my head spin
-------------------------------------

Also I am having problems with Math.random(). I've seen some GM scripts that use it but I am not able to get it to run in mine?

This post has been edited by mumeichan: Nov 13 2009, 01:04 PM
User is online!Profile CardPM
Go to the top of the page
+Quote Post

Bump TopicReply to this topicTopic OptionsStart new topic
 



----debug section please ignore----
Lo-Fi Version Time is now: 23rd November 2009 - 12:04 PM
All Rights Reserved 2003-2009 Vijandren Ramadass (~living on a prayer~)