What could be causing the defaultOpen feature to function on my code simulator but fail to work on my website?

I have a set of tabs on my website, and I want the first tab to be automatically selected when the page loads. I tried using some Javascript code from w3schools, which worked in a simulator, but now it's not working on my actual site, and it looks terrible.

Here is the relevant part of the code that I used:

document.getElementById("defaultOpen").click();

function openTab(evt, tabName, boxName) {    
var i, tabcontent, tablinks;

var box = document.getElementById(boxName);

tabcontent = box.getElementsByClassName("sg-tab-content");
for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
}

tablinks = box.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" sg-current", "");
}

document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " sg-current";
}
And:
<div class="code-tabs">
  <button class="tablinks" onclick="openTab(event, 'disp-Deck','code-box-1')" id="defaultOpen" style="background-color:#FF8B53">Deck</button>
  <button class="tablinks" onclick="openTab(event, 'disp-Hand','code-box-1')" style="background-color:#FF8B53">Hand</button>
  <button class="tablinks" onclick="openTab(event, 'disp-Field','code-box-1')" style="background-color:#FF8B53">Field</button>
  <button class="tablinks" onclick="openTab(event, 'disp-Graveyard','code-box-1')" style="background-color:#FF8B53">Graveyard</button>
  <button class="tablinks" onclick="openTab(event, 'disp-Banished','code-box-1')" style="background-color:#FF8B53">Banished</button>
  <div class="spacer"></div>
</div>
<pre id="disp-Deck" class="sg-tab-content">
    <p><mark>Deck!</mark></p>
</pre>

EDIT: Removed the website link since the issue has been resolved, and I'm continuing work on my site :)

This code is still a work-in-progress for someone who is new to web development. Even though I followed all the instructions I could find, it's still not functioning properly. Any suggestions?

Answer №1

Upon reviewing your website, it seems that the code layout needs some adjustments.

I noticed two issues:

  • The JavaScript function creating the click event may be running before the relevant HTML content is fully loaded (check for any errors in the browser console)

  • The style element is located within the body section instead of the head section where it should be

The first issue could potentially be causing the problem you are experiencing, although I wasn't able to replicate it due to server differences.

Below is a rearranged snippet of the code for you to test:

function openTab(evt, tabName, boxName) {
  var i, tabcontent, tablinks;

  var box = document.getElementById(boxName);

  tabcontent = box.getElementsByClassName("sg-tab-content");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  tablinks = box.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" sg-current", "");
  }

  document.getElementById(tabName).style.display = "block";
  evt.currentTarget.className += " sg-current";
}

document.getElementById("defaultOpen").click();
/* CSS styles */
<html>
<head>
  <style>
    /* CSS styles here */
  </style>
</head>
<body>

  <h1>
    Testing center
  </h1>
  <div id="code-box-1">
    <div class="code-tabs">
      /* Tab buttons and content */
    </div>
    <pre id="disp-Deck" class="sg-tab-content" style="display: none;">        <p><mark>Deck!</mark></p>
    </pre>
    <pre id="disp-Hand" class="sg-tab-content" style="display: none;">        <p><mark>Hand!</mark></p>
    </pre>
    <pre id="disp-Field" class="sg-tab-content" style="display: none;">        <p><mark>Field!</mark></p>
    </pre>
    <pre id="disp-Graveyard" class="sg-tab-content" style="display: block;">        <p><mark>Graveyard!</mark></p>
    </pre>
    <pre id="disp-Banished" class="sg-tab-content" style="display: none;">        <p><mark>Banished!</mark></p>
    </pre>
  </div>
  <script type="text/javascript">
    // Javascript function here
  </script>
</body>

Feel free to try this rearranged code on your server environment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...

The integration of ngx-translate with an HTTP interceptor is currently experiencing difficulties

Using ngxtranslate for application translation has been seamless so far. However, I am facing an issue with the HttpInterceptor. This interceptor attempts to retrieve data from local storage at the start and displays a dialog prompting you to either load t ...

Tips for concealing validation errors in React Js when modifying the input field

I have recently started working with ReactJs, and I've implemented form validation using react-hook-form. After submitting the form, the errors are displayed correctly. However, the issue arises when I try to update the input fields as the error messa ...

Ensure the footer remains fixed while scrolling

For the past day, I've been tackling a challenge with my online shop project. On the specific item's page, I want to include a fixed [add to cart] button as a footer initially, which then becomes sticky when scrolling to a certain point. You can ...

Tips for securing a navbar in material ui

https://i.stack.imgur.com/CYfmQ.png In my current React project, I am facing an issue with aligning components within the Material-UI AppBar Component. My aim is to achieve a seamless and perfectly straight alignment for three key elements: a logo image, ...

What is the method for retrieving Polymer data that has been bound and incorporating it into a script?

My current setup involves utilizing the <firebase-document> element to retrieve data from Firebase. The data is then bound to {{poster}}, which allows me to access details of the poster object using its keys. For instance, {{poster.name}} displays th ...

Solving CORS issue between Vue.js and Spring Boot

Access to the audio file at 'https://.amazonaws.com/.mp3' from origin 'http://localhost:8080' has been restricted by CORS policy: The requested resource does not have the 'Access-Control-Allow-Origin' header We are using a vu ...

Choosing the Laravel 6 option for editing via AJAX: A step-by-step guide

I am looking to update a user who resides in a specific state within a country. The country and state fields are dropdown select options, with a relationship established between them and the user. The state field is populated based on the selected country. ...

Can you explain the true meaning behind the phrase " '+movie['x']+' "?

Initially, I was supposed to pass this value into the function. However, it only worked once I started using quotations like this: " ' + some value + ' ". What could be the significance of this? ...

Designing HTML Emails Using Nested Tables

Why is my text-decoration="none" not displaying properly? I have tried placing it in various locations like table, tr, td, but I am unable to make it work. Are there any common mistakes when styling email designs? Here is the code snippet: <table cel ...

Utilizing the array reduce method in combination with promises

I am working on a function that extracts data from the current path to create an array ([x, y, z, a, b]). This array is then passed into the reduce method to generate a new array of objects. My goal is to pass each value from the initial array into a fun ...

converting an array to JSON format results in a string

I'm attempting to perform an ajax call to a PHP file that will create an array, convert it to JSON, and then display the first item in the array using console.log. Currently, I have this code snippet on my homepage: <script> wi ...

Issues with navigating jQuery UI links while offline in Google abound

Hello, I am a newcomer to jQuery and I am facing an issue with my code. I added the <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> but for some reason, my jQuery is not working. I have tried searching ...

Creating a Web Form in Outlook Using the POST Method

Seeking help in creating an HTML email featuring two interactive buttons - Approve and Reject. I have successfully generated the HTML email and sent it to Outlook. Snapshot: https://i.sstatic.net/NrGFM.png The HTML code within the email: <!DOCTYPE ...

Issue with Java Script inheritance in google.maps.OverlayView not functioning as expected

UPDATE: After spending another day working on this, I believe I have identified the issue, although it is not yet confirmed. Once I have verified the solution, I will update this post with an answer. My current understanding is that the problem arises fro ...

Error: export keyword used incorrectly

Currently, I am in the process of developing an npm package called foobar locally. This allows me to make real-time changes and modifications without the need to constantly publish and unpublish the package, which greatly improves my development efficiency ...

What is the CSS technique for concealing the content of an ordered list item while retaining the marker?

In our order process, we utilize an ordered list to display the steps in sequence: <ol> <li>Products</li> <li class="active">Customer</li> <li>Payment</li> </ol> On desktop view, it appears a ...

Using jQuery to trigger an event when an element is empty or when the element contains children nodes

Is there a way to create a jQuery script that can monitor the children of an element? If the element does not have any children, default scrolling for the entire page is enabled. If the element has children, scrolling for the whole page is disabled. The ...

CURL is spitting out garbage data

I've been attempting to scrape data from the 538 baseball odds website. When I paste the URL into Chrome and check the source code, it appears to be standard HTML. However, when I try to extract the data using the following code snippets or file_get ...

Using jQuery to combine a conditional statement with a click event and disabling a button using the `.prop('disabled', true)` method

Looking for some assistance with this issue I've encountered. After researching on StackOverflow, I managed to find a solution to disable button clicking if the form is left empty using the $.trim(.....) code below! Success! However, adding that part ...