I have made multiple divs with unique ids of the same “tabContent” class. The goal is to have the div with id = “0” to be clicked/open by default, and all the other divs are only displayed when their corresponding tabs are clicked. Currently, the divs are connected to the tabs, but by default all the contents of all divs are shown. I tried to correct this by initialising the the first tab (id=“0”) as clicked, but it doesn’t seem to have done anything.
Here is my JS function for hiding and showing tabs on the page:
const selectTab = function(event){
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName(“tabContent”);
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = “none”;
}
show(event); //Just contains: document.getElementById(event).style.display = “block”;
}
Here is the the function at the top of my file that attempts to initialise the the first tab (id=“0”) as clicked:
window.onload = function () {
document.getElementsByClassName(‘tabContent’)[0].click()
};
I suppose I could default display: hidden all the divs except for the one with id=“0” in a in-line style, but I feel like there is a better way of doing this? Not sure why the above is wrong either.
You are very close! There are two ways to make this work. Using your approach, to programmatically fire a click event, you need to use dispatchEvent since the click() function doesn’t always work on many elements:
var mouseEvent = new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
});
var firstTab = document.getElementsByClassName(‘tabContent’)[0];
firstTab.dispatchEvent(myEvent);
This article goes into more detail on where this is coming from.
The second approach (which I prefer) is to have a function whose sole job it is to set the default state of your app. When your page loads, this function calls and sets the visibility/display of the elements based on what you want.
Tried the first approach and added an event listener since the article mentioned needing one, but i’m getting an error “TypeError: Cannot read property ‘addEventListener’ of undefined”?
var mouseEvent = new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
});
var firstTab = document.getElementsByClassName("tabContent")[0];
firstTab.addEventListener(mouseEvent, selectTab, false);
firstTab.dispatchEvent(mouseEvent);
The error means that the firstTab element isn’t getting found. This means that document.getElementsByClassName isn’t returning an element. How are you specifying your JS? Is it located in the same document alongside your HTML? Or are you loading it from an external JS file? (I’m trying to see if your code is running before the HTML/DOM has fully loaded - see this article for more info ).
Thanks! My guess is that your JavaScript fully runs before your React code has had a chance to put the elements in the DOM. One approach would be to put all of your JavaScript inside the componentDidMount lifecycle method: