Colin Sygiel Colin Sygiel - 21 days ago 5
Javascript Question

How can I modify my function to hide the body of the messages as default and to show the body when clicked?

Here is my html with the JS within. The function "toggleMessage()" is the function I am using to hide and show messages when clicked. The problems I am running into include:


  1. Messages showing by default, when they should hide by default (until clicked).

  2. When clicked, all messages show at once - I want only the messages clicked on to show.

  3. The new messages that populate the page every 3 seconds are not affected by the click event - I want them to be effected.



function newMessage() {
// Loop goes through emails and creats divs for subject, date, sender, and body
var i = 0;
while (i < window.geemails.length) {

//email container
var div = document.createElement("div");

//date
var dateField = document.createElement("h1");
dateField.className = "date";
dateField.innerHTML = window.geemails[i].date;
div.appendChild(dateField);

//subject
var subjectField = document.createElement("h1");
subjectField.className = "subject";
subjectField.innerHTML = window.geemails[i].subject;
div.appendChild(subjectField);

//sender
var senderField = document.createElement("h1");
senderField.className = "sender";
senderField.innerHTML = window.geemails[i].sender;
div.appendChild(senderField);

//body
var bodyField = document.createElement("p");
bodyField.className = "body";
bodyField.innerHTML = window.geemails[i].body;
div.appendChild(bodyField);

//Separate message content into containers
document.getElementById("main").appendChild(div);

//inbox counter
document.getElementById('counter').innerHTML = "You have " + document.getElementsByClassName("date").length + " messages";

window.geemails.shift();
}

}


newMessage();



//interval for loading new messages
function addNewMessage() {
setInterval(function() {
window.geemails.push(getNewMessage());
newMessage();
}, 3000);
}

addNewMessage();

//hiding and showing body message upon click
var messageBox = document.getElementsByClassName("subject");

for (var i = 0; i < messageBox.length; i++) {
messageBox[i].addEventListener("click", toggleMessage);
}

function toggleMessage() {
var showMessage = document.getElementsByClassName('body');
for (var i = 0; i < showMessage.length; i++) {
if (showMessage[i].style.display === 'none') {
showMessage[i].style.display = "block";
} else {
showMessage[i].style.display = "none";
}
}
}



Answer

You need a class for your messages and possiblt for their bodies. Suppose you have a message div with a message body like this

 <div class="message">
     <div class="message-header">
     </div>
     <div class="message-body" style="display:none;">
     </div>
 </div>

if you want the body to be hidden by default use css display:none

then in your javascript do

$('.message').click(function(){
      $(this).children('.message-body').show();
});
Comments