Colin Sygiel Colin Sygiel - 4 months ago 18
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");

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

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

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

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

//Separate message content into containers

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




//interval for loading new messages
function addNewMessage() {
setInterval(function() {
}, 3000);


//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";


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 class="message-body" style="display:none;">

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

then in your javascript do