In my website, the user has an a text area where he/she can enter text or images for a post then clicks the a button. The button clicked is linked to a java script function that dynamically creates an article element containing the post content and the username and profile picture. The code I have creates the new article element alright, but I am facing two problems:
- Whenever I click post again, it creates a new article element inside the previous one.
- I need the img element created to not have a fixed src.
Here is my html for this part
<article class="posts">
<img id = "profilePic" class="peopletofollowimg" src=Profile.jpg alt="View Profile Picture">
<textarea id="posting-area" rows="6" cols="90" placeholder="Share Your Thoughts!"></textarea>
<button onclick="createPost()" id="post-button">Post!</button>
</article>
<article id="myarticle" class="posts">
</article>
And here is my js code
<script>
document.getElementById("post-button").onclick = createPost;
var el = document.getElementById("post-button");
if (el.addEventListener)
el.addEventListener("click", createPost(), false);
else if (el.attachEvent)
el.attachEvent('onclick', createPost());
function createPost(){
var article = document.createElement("article");
article.setAttribute("id", "myarticle");
article.className = "posts";
var p = document.createElement("p");
//p.setAttribute("id", "postContent");
p.innerHTML = document.getElementById("posting-area").value;
var img = document.createElement("img");
//img.setAttribute=("src", document.getElementById("profilePic"));
// img.innerHTML = document.getElementById("profilePic");
img.getAttribute("src");
img.className = "peopletofollowimg";
// test case, append the content
document.body.appendChild(article);
document.getElementById("myarticle").appendChild(p);
document.getElementById("myarticle").appendChild(img);
}
</script>
addEventListenerandattachEventmust becreatePost, notcreatePost().img.getAttribute("src")doesn't do anything. It returns the source, but doesn't do anything with it.