Using JavaScript to fully load a webpage, rather than just loading a specific div

As a JavaScript beginner, I've encountered what seems to be a simple issue. I am trying to dynamically change the content of a div based on which button is clicked. This code snippet functions properly in JSfiddle, but when I transfer it to my local machine, the entire webpage loads instead. Even wrapping the JavaScript with $(window).load(function(){ ... }) does not solve this problem.

Here's my HTML:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script src= "http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="script.js"></script>


</head>

<body>


<ul class="menu">
  <li><a href="#about" class="menu-btn">About</a></li>
  <li><a href="#contact" class="menu-btn">Contact</a></li>
  <li><a href="#misc" class="menu-btn">Misc</a></li>
</ul>

<div id="about" class="menu-content">About</div>
<div id="contact" class="menu-content">Contact</div>
<div id="misc" class="menu-content">Misc</div>


</body>

</html>

My JavaScript (script.js):

$(window).load(function(){


  var $content = $('.menu-content');

  function showContent(type) {
    $('div', $content).hide();
    $('div[data-menu-content='+type+']').show();
  }

  $('.menu').on('click', '.menu-btn', function(e) {
    showContent(e.currentTarget.hash.slice(1));
    e.preventDefault();
  });

  showContent('about');
});

Answer №1

$(window).load(function(){ ... })

substitute with:

$(document).ready(function(){ ... })

Answer №2

Switch out your (window).load with (document).ready

load is triggered when all content, including images, has finished loading. On the other hand, ready is activated when the DOM is ready for user interaction.

load()

The load event occurs at the conclusion of the document loading process. At this moment, all elements in the document are part of the DOM, and all images and sub-frames have completed loading.

ready()

Even though JavaScript offers the load event to execute code once a page is displayed, this event only triggers after all assets like images have been fully loaded. Typically, scripts can run as soon as the DOM hierarchy is fully built. The function passed to .ready() is ensured to run after the DOM is prepared, making it the ideal place to attach additional event handlers and execute more jQuery code. When working with scripts that depend on CSS style properties, it's essential to link external stylesheets or include style elements before referencing the scripts.

Answer №3

give this a shot

$(document).ready(function(){ 


  var $content = $('.menu-content');

  function displayContent(category) {
    $('div', $content).hide();
    $('div[data-menu-content='+category+']').show();
  }

  $('.menu').on('click', '.menu-btn', function(event) {
    displayContent(event.currentTarget.hash.slice(1));
    event.preventDefault();
  });

  displayContent('info');
});

Answer №4

Here is a suggestion for you to consider:

function displayContent(category) {
    $($content).hide();
    $('#'+category).show();
  }

After testing your code on my computer, it became evident that Jquery was having difficulty locating the specified div using the provided selectors upon initialization.

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

Showcasing menu options in a double-column layout - MUI Menu

Just starting out with React. I'm using MUI menu to display items in two columns, but I've noticed a significant gap between the menu items when using grid display with repeat 2 and 1fr. display:'grid' , gridTemplateColumns : 'repe ...

Attempting to achieve a fixed element using jQuery Waypoints

Trying to create a sticky div that scrolls up or down the page (onClick) based on its position. Tweaked the code but still searching for the magic formula. Using plugins from: and Here's the code snippet. <head> <script src="http://cod ...

Suitable HTML container for ASP form over HTML table

Can anyone advise on the best HTML container to use for an ASP form that can be styled with CSS instead of an HTML table? For example, consider the following form on an aspx page: <form id="WPF" runat="server"> <asp:Label ID="lblCCode" Text="Cou ...

Confirm that the input value consists of x numeric characters

Looking to validate an input field that must contain a minimum of x amount of numeric characters. For example, let's say I require the input value to have at least 5 numeric characters: 12345 - valid AB12345 - valid 123456 - valid AB312312 - valid a ...

What is the process of transferring information from an HTML form to a Django form?

Creating an HTML form: <form method="post" action="{% url 'blog:add_comment' article.id %}"> {% csrf_token %} <textarea type="text" id="text" class="form-control" rows="3&quo ...

Tips for accessing values from a dynamically generated checkbox group using jQuery upon page load

My task involves retrieving the values of the checked checkboxes from 2 groups of checkboxes. These 2 groups are not present in the HTML file but are dynamically generated using jQuery when the page loads. I need to create 2 functions, getSubjects() and ge ...

Scrolling horizontally in vue-chartjs-chartwidget

I have a question regarding vue-chartjs. I am looking to achieve a similar result to the one demonstrated in this jsfiddle example: http://jsfiddle.net/mbhavfwm/ Below is the code for my Vue.js component (Chart data is passed through params). &l ...

implementing nested key property specifications in React

Is it recommended to explicitly set the keys for the children of components when using arrays of Components? I understand that when using arrays of Components the key property is assumed to be the index of the array and should be explicitly set. {arr.ma ...

Access a PDF document through an AJAX POST request

I have an ajax POST method that looks like this: $.ajax({ type: 'POST', url: rootUrl("Home/PrintInvoice/12"), success: function (result) { $("#TestInvoicePrint").empty(); $("#TestInvoicePrint").html(result); w ...

Animation with multiple meshes in Three.js

Having just started working with threejs, I decided to use a for loop to create 400 cylinders. The rendering of the objects in the scene works perfectly. However, when it comes to animating the cylinders, only one out of the 400 seems to rotate. How can I ...

Find all relevant employee information at once without the need for iteration

I have structured two JSON arrays for employee personal and company details. By inputting a value in the field, I compare both tables and present the corresponding employees' personal and company information in a unified table. <html> ...

Calculate the total count of non-null entries within a table

Is there a method to count the number of non-empty inputs in a table? I have attempted the following: $("#template_item_table").find('input[value!=""]').length However, I keep getting this error message: Uncaught Error: Syntax error, unrecogn ...

What is the best way to implement target="_blank" in an anchor tag using 'sanitize-html'?

In my current project, I am utilizing the sanitize-html library. Let's say I receive an email containing an anchor tag like this: this is to test something <a href="https://www.google.com/">open google</a> When this email shows up in my ...

What is the most efficient way to calculate the current percentage of time that has elapsed today

Is there a way to calculate the current time elapsed percentage of today's time using either JavaScript or PHP? Any tips on how to achieve this? ...

Stop the page from scrolling when a modal is displayed in React

I've encountered an issue with my custom modal component where the background stops scrolling when the modal is open. Initially, I attempted to solve this by using the following code: componentDidMount() { document.body.style.overflow = 'hi ...

The closest() method in Jquery is not functioning properly when attempting to remove a specific

I'm encountering an issue with a script that adds rows to capture information for an additional visitor in a SharePoint List Form. The problem arises when trying to add a new visitor after removing one - it brings back the previously removed rows alon ...

The font displayed by Google looks black when viewed on iPhones, while it appears in its true color on all other

When I was optimizing my website for mobile devices, I noticed that the font size needed adjustment. Surprisingly, on Android phones, the text appeared in orange and normal, while on Safari and Chrome on iPhones, it didn't display correctly. I have i ...

Sharing data between child and parent components in Angular2: a comprehensive guide

I am facing an issue with transferring a range of values from a child component to a parent component. Below are the details of my components: TS: import { Component, EventEmitter, Output, OnChanges, SimpleChanges } from '@angular/core'; @Com ...

Excluding child elements in JQuery

My DOM object contains the following HTML: <div class="parent"> this is my <span>11</span> original text i <span>23</span> want <div class="child1">Lorem Ipsum is simply dummy text</div> <div class= ...

Assistance with utilizing Regular Expressions to extract the className from a React/JSX component

For instance, I have <img className='class' src='somelink' /> and my goal is to extract only the className='class'. I have already attempted using / className='.+'[ |>] while going through files in search of ...