I’m new to javascript and I am attempting to create an element with certain html inside.
This is my code:
function newTask()
{
var newtask = document.CreateElement('li');
newtask.setAttribute('id','newtask');
newtask.innerHTML="DeveloperSnippets";
document.getElementById('newtaskcontainer').appendChild(newtask);
document.getElementById('newtask').innerHTML='<input type="text" size="" value="Click here to add new task"> <a href=""><img src="IMG/delete.png" alt="delete" class="fr" /></a>';
}
I beleive that is right but I don’t know how to get that to fire when a user clicks on a button.
I have this code in an external js file so I dont want to have to have any inline javascript.
UPDATE
Hey, thanks for all your help guys, I was having problems linking with my JS file which was the reason why none of your code would work, but by time I realized the problem I had already found out the code myself. But you guys can still help me if you want 🙂
This is what I have got now:
function newTask()
{
var addTask= document.createElement("div");
addTask.id = "newtask";
addTask.innerHTML = "/* My HTML */"
document.getElementById("newtaskcontainer").appendChild( addTask);
$("#newtask").animate({opacity: "1.0", left: "+=1000"}, 500);
}
Unfortunatly, I had to use a html onclick attribute, but for now that will do. The problem I do have with, is because of the last line of code
$("#newtask").animate({opacity: "1.0", left: "+=1000"}, 500);
it isn’t creating anymore divs, it just keeps on pushing the div to the side, and what I need it to do, is create a div that slides in from the left (which it does), but then when I click the button to get a new div, it actually created a new div instead of just pushing the previous div further to the right.
I hope that makes sense, and thank you all so much for your help.
The simplest way there is is to assign the function as the
onclickhandler.Event listeners are the more professional way to go, especially since they add event handlers instead of overwrite (like
onclick) does, but since neither the W3C model nor the Microsoft model works in all browsers, it might be best to use a framework like jQuery to achieve that more robust behavior, if required.