Don't set up events with HTML event attributes. Here's why.
Also, don't use inline styles when you can use classes. Classes are reusable and don't clutter up the code. They also are easier to work with in JavaScript.
See comments inline for additional details:
// Get all the div elements to be cycled through into a node list
var divs = document.querySelectorAll(".cycle");
// Loop through each div in the array...
for(let i = 0; i < divs.length; i++) {
// Assign a callback function for the click event of the div
divs[i].addEventListener("click", function(){
divs[i].classList.toggle("hidden"); // Hide the current div
// Check to see if there is another div after the current one
if(i < divs.length -1){
divs[i+1].classList.toggle("hidden"); // Hide the next div
} else {
divs[0].classList.toggle("hidden"); // Hide the first div
}
});
}
/* Everything that should not be seen by default
should have this class set up on it in the HTML */
.hidden { display:none; }
/* Just for fun */
.cycle {
background-color:aliceblue;
font-family:Arial, Helvetica, sans-serif;
font-size:2em;
box-shadow:2px 2px #e0e0e0;
width:50%;
padding:1em;
user-select:none;
cursor:pointer; /* Let user know they can click on the element */
}
<div id="main_place1" class="cycle">main</div>
<div id="one" class="hidden cycle">one</div>
<div id="two" class="hidden cycle">two</div>
<div id="three" class="hidden cycle">three</div>
Now, depending on what the content of each div
is supposed to be, it may be simpler to use just one div
that is always visible, but upon each click, just replace the contents of that div
. The content could be stored in an array. This would not only be simpler in terms of not having to worry about toggling the display
of the various div
elements, but it would be more efficient.
/* This code should be placed inside of a <script> element that comes
just before the closing body tag (</body>) */
// Content for the div is stored here:
var content = ["main", "one", "two", "three"];
// Get reference to the div that will hold the content
var div = document.querySelector(".cycle");
var contentIndex = 0; // Represents which element in the array is currently displayed
// Initialize the default content of the div
div.textContent = content[contentIndex];
// Assign a callback function for the click event of the div
div.addEventListener("click", function(){
// Increment the contentIndex unless we are at the end of the array
contentIndex = (contentIndex < content.length - 1) ? ++contentIndex : 0;
// Set the content to the appropriate value
div.textContent = content[contentIndex];
});
/* Just for fun */
.cycle {
background-color:aliceblue;
font-family:Arial, Helvetica, sans-serif;
font-size:2em;
box-shadow:2px 2px #e0e0e0;
width:50%;
padding:1em;
user-select:none;
cursor:pointer; /* Let user know they can click on the element */
}
<div id="main_place1" class="cycle"></div>