Using JQuery to hide elements by setting CSS display as none instead of block

Is there a way to change the display of a content div to block when a specific tab is selected by the user, while hiding all other content divs?

Here is the JQuery code I have tried so far:

$(document).ready(function() {
  function resetTabs() {
    $("#content > div").hide();
    $("#tabs a").attr("id", "");   
  }

  var myUrl = window.location.href;
  var myUrlTab = myUrl.substring(myUrl.indexOf("#"));
  var myUrlTabName = myUrlTab.substring(0, 4);

  (function () {
    $("#content > div").hide(); 
    $("#tabs li:first a").attr("id", "current");
    $("#content > div:first").fadeIn(); 

    $("#tabs a").on("click", function (e) {
      e.preventDefault();
      if ($(this).attr("id") == "current") {
        return
      }
      else {
        resetTabs();
        $(this).attr("id", "current"); 
        $($(this).attr('name')).fadeIn();
      }
    });

    for (i = 1; i <= $("#tabs li").length; i++) {
      if (myUrlTab == myUrlTabName + i) {
        resetTabs();
        $("a[name='" + myUrlTab + "']").attr("id", "current");
        $(myUrlTab).fadeIn();
      }
    }
  })()
});


$(document).ready(function() {
  $("#tabContent1").load("test.txt");
  $('a[name="#tab2"]').click(function() {
    $("#tabContent2").load("test.txt");
  });
});

Here is the HTML structure I'm using:

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="CSS/common.css" />
    <script src="JS/common.js"></script>
    <title></title> 
  </head>
  <body>
    <nav>
      <ul id="tabs">
        <li><a href="#" id="tab1" name="#tab1">Home</a></li>
        <li><a href="#" id="tab2" name="#tab2">History</a></li>
        <li><a href="#" id="tab3" name="#tab3">Specifications</a></li>
        <li><a href="#" id="tab4" name="#tab4">Gallery</a></li>    
      </ul>
    </nav>
    <div id="content">
      <div id="tabContent1"></div>
      <div id="tabContent2"></div>
      <div id="tabContent3"></div>
      <div id="tabContent4"></div>
    </div>
  </body>
</html>

I've encountered the following error while implementing this:

Uncaught TypeError: Object #tabContent2 has no method 'fadeIn'
i
st.event.dispatch 
st.event.add.y.handle

Answer №1

What is the connection between tabContent and the tabs? One way to ensure a stronger connection is by setting the name of the tabs to correspond with the actual content id's, as shown below:

<nav>
  <ul id="tabs">
    <li><a href="#" id="tab1" name="#tabContent1">Home</a></li>
    <li><a href="#" id="tab2" name="#tabContent2">History</a></li>
    <li><a href="#" id="tab3" name="#tabContent3">Specifications</a></li>
    <li><a href="#" id="tab4" name="#tabContent4">Gallery</a></li>    
  </ul>
</nav>
<div id="content">
  <div id="tabContent1"></div>
  <div id="tabContent2"></div>
  <div id="tabContent3"></div>
  <div id="tabContent4"></div>
</div>

By following this structure, the function $($(this).attr('name')).fadeIn(); should operate more effectively.

Answer №2

experiment with this method to achieve a smoother fadeIn effect

let currentTitle = $('#current').attr('name');
$(currentTitle).fadeIn();

try this approach instead of

$($(this).attr('name')).fadeIn();

(Oops, don't forget to review the changes)

Answer №3

Thanks to the helpful tips from @Jaco Koster's JSFiddle and some JQuery magic, I finally got everything working smoothly.

$(document).ready(function () {
  $("#tabContent1").load("test.txt");

  $('a[name="#tabContent1"]').click(function () {
    $("#tab2").removeClass('activeTab');
    $("#tab3").removeClass('activeTab');
    $("#tab4").removeClass('activeTab');
    $(this).addClass('activeTab');
    $("#tabContent1").load("test.txt");
    $("#tabContent1").show();
    $("#tabContent2").hide();
    $("#tabContent3").hide();
    $("#tabContent4").hide();
  });

  $('a[name="#tabContent2"]').click(function () {
    $("#tab1").removeClass('activeTab');
    $("#tab3").removeClass('activeTab');
    $("#tab4").removeClass('activeTab');
    $(this).addClass('activeTab');
    $("#tabContent2").load("test2.txt");
    $("#tabContent2").show();
    $("#tabContent1").hide();
    $("#tabContent3").hide();
    $("#tabContent4").hide();
  });

  $('a[name="#tabContent3"]').click(function () {
    $("#tab1").removeClass('activeTab');
    $("#tab2").removeClass('activeTab');
    $("#tab4").removeClass('activeTab');
    $(this).addClass('activeTab');
    $("#tabContent3").load("test3.txt");
    $("#tabContent3").show();
    $("#tabContent1").hide();
    $("#tabContent2").hide();
    $("#tabContent4").hide();
  });

  $('a[name="#tabContent4"]').click(function () {
    $("#tab1").removeClass('activeTab');
    $("#tab2").removeClass('activeTab');
    $("#tab3").removeClass('activeTab');
    $(this).addClass('activeTab');
    $("#tabContent4").load("test4.txt");
    $("#tabContent4").show();
    $("#tabContent1").hide();
    $("#tabContent2").hide();
    $("#tabContent3").hide();
  });
});

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

Is it necessary to properly close meta and link tags in HTML documents?

As I inspected someone's HTML, I noticed that they didn't close the meta and link tags in the head section. Surprisingly, the code still worked perfectly fine; does this mean closing these tags is purely optional? I always believed that leaving ...

React's Dynamic Table fails to rerender when updated values are placed in the same row and under the same header

Here is the table generated by my functional component: <table class="table"> {/* Consonant Table */} <tr> <th colSpan="2">---</th> {headersPOA. ...

Show the value of a JavaScript object in VueJS

New to Vue and need some guidance... I'm having trouble accessing the values in a JS object displayed in the DevTools within one of my routes in a Vue app. Specifically, how can I display the values from filteredData:Array[1]? https://i.sstatic.net/ ...

Personalized Tumblr-style button

Hey there, I've been working on creating a custom Tumblr-like button and tried adding an iframe above it to make it clickable. However, something seems to be off as it's not functioning properly. I'm still trying to wrap my head around how i ...

When trying to access localhost:5000, the index.js file is unable to retrieve /

const NutritionAPI = require('./nutritionapi'); const nutService = new NutritionAPI('50cee42503b74b4693e3dc6fccff8725','2755697297a84ac5a702461b166e71f6'); // Setting up Express webhook const express = require('express&ap ...

Tips on preventing the opening of a new browser tab by using Ctrl + click

Hey there, I've got a list of products that can be selected using the Ctrl key. $(parentSelector).on("click", function (evnt) { evnt.stopImmediatePropagation(); var item = $(evnt.delegateTarget) ...

Exploring JavaScript: Accessing an array object within another object

I'm having trouble accessing an array object within an object in JavaScript. The object structure is as follows: categories: Array(5) 0: name: "Electronics" subCategories: Array(16) 0: name: "Video Games & Accessories" __typena ...

Ways to solely add effect to background image without affecting text

I'm on a quest to find a way to create a CSS effect that only applies to an image, excluding the letters and buttons. I need to establish a rule in my CSS without altering the current structure. The issue arises when my code ends up applying the effec ...

I noticed an excess of white space on the right side of my Angular website

Check out my website here. Everything seems to be functioning correctly, however, there is an issue with scrolling on mobile. It should only scroll up and down, not left and right! I have noticed a strange white space on the right side of my site when view ...

Dual Camera Toggle Functionality with Three.js Orbit Controls

I am facing an issue with two cameras in one scene, one viewport, and one renderer. I switch between cameras using HTML buttons. ISSUES Issue 1 When using camera1, there is no response from moving the mouse. However, when I switch to camera2, the orbit ...

Exploring nested hash maps within JavaScript

Having some trouble with creating a nested hash map in JavaScript (js), similar to the example below: let rooms = {}; rooms[roomNum][personName] = somethings; However, I keep encountering an error when attempting this: TypeError: Cannot set property &apo ...

Submitting a form using jQuery and processing the response

Can a form be submitted using jQuery without utilizing json, ajax, or other methods for handling the result? For example: <form id="loginform"> //some input fields and a submit button. </form> And then with jQuery: $("#loginform").sub ...

What could be causing my asynchronous JavaScript/Node.js function to bypass a significant portion of the code?

Upon calling the function below: async function sql_func(){ console.log('anothertest') async () => { console.log('third test') try { await sql.connect('heres the connection data') ...

Fixed header in a div, allowing content to scroll when hovering over the header

How can I ensure that the header remains fixed at the top while allowing the content to scroll when hovered over? The current issue is that when a user hovers over the header and tries to scroll, the content does not move. body { margin: 0; ...

The for each loop fails to return the value

In my Vue component, I have a conditional loop that iterates through train stations with 'New York' as the destination or on the route. <tr v-for="departure in filterTrainStations" :key="departure.name"> <td>{{ departure. ...

modifying the identification value in HTML and then reverting it

Although this may seem like messy code, I'm really in need of assistance with a problem that has stumped me. Currently, I am working on an E-shop project where I have modals for displaying products. Within these modals, there is a button that allows u ...

What could be the reason why my POST endpoint isn't able to receive this AJAX request?

I am currently working on a JavaScript function that is supposed to send JSON data to my escreve POST REST method. $(document).ready(function() { $("#idform").on('submit', function(e) { e.preventDefault(); alert($("#idform"). ...

Adjusting border width in Firefox with HTML buttons

Here is the HTML button I am working with: <input ID = "btnModel" value="Submit"> This is how it appears in Firefox: However, when I assign a border-width to it: input#btnModel{ border-width:2px; } it changes to this: 1- It does not revert ...

Determining the navigation changes within a React browser

Hi there, I'm using browserHistory.goForward() and browserHistory.goBack() to navigate forward and backward in my app with arrow buttons. However, I need a way to determine if the route has actually changed after executing browserHistory.goForward/goB ...

Emphasize today's date on the w3widgets adaptable calendar

While developing a website featuring a calendar to showcase events, I came across w3widgets, which proved to be quite helpful. However, I encountered an issue when trying to highlight the current date on the calendar. It seems that the calendar only highli ...