What is the best way to determine which CSS class is shown when the page is loaded using JQuery?

I am facing a dilemma with displaying my site logo. I have both an image version and a text version, and I want to choose which one to display based on the vertical position on the page and the screen width.

<a class="navbar-brand" id="top-logo" href="#top"><img src="display_board.png" alt="Page Title"></a>
<a class="navbar-brand scroll" id="bottom-logo" href="#top">Page Title</a>

The current script handles screen resizing and scrolling once the page is loaded. However, there is an issue when loading the site on mobile devices - the image logo briefly shows before switching to the text logo, as the script file loads at the end of the HTML file.

var method_update_nav = function() {
  var buffer = 200;
  var horizontal_switch_point = 1200;
  var vertical_switch_point = $('.carousel-indicators').offset().top - buffer;
  var window_top = Math.round($(window).scrollTop());

  if ($(window).width() <= horizontal_switch_point || window_top >= vertical_switch_point) {
    $('nav').removeClass('top');
    $('nav').addClass('bottom');
    $('#top-logo').hide();
    $('#bottom-logo').show();
  } else {
    $('nav').removeClass('bottom');
    $('nav').addClass('top');
    $('#top-logo').show();
    $('#bottom-logo').hide();
  }
};

var main = function() {
  /* UPDATE NAV */
  method_update_nav();
  $(window).resize(method_update_nav);
  $(window).scroll(method_update_nav);
}

$(document).ready(main);

If I load the script in the HTML <header>, it doesn't work because the classes referenced by JQuery are not defined yet in the HTML tags.

Is there a way to determine the correct class to show when the page loads, after the classes have been defined in the HTML tags?

Answer №1

When the script is loaded in the HTML header, it doesn't work properly because the classes referenced by jQuery are not yet defined in the HTML tags.

It's as you mentioned!

So, since you're using jQuery, make sure to place the script that references HTML elements at the bottom of the page within:

$(document).ready(function(){
    //script can now access the values since the HTML has been fully loaded
})

I recommend looking up some tutorials online for more guidance.

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

Angular 1.4.8 Issue: [$injector:modulerr]

I can't seem to identify the main cause of this error. I consistently see a green underline below the word angular in my javascript file. I'm not sure why. (Using Visual Studio Code) HTML <html ng-app="myapp"> <head> ...

Mysterious additional spacing

I am facing an issue with aligning my div elements with a 20px margin. Despite setting the margin to 20px, I notice that there are additional 4 pixels rendered when I view it on the browser. Below is the code snippet: .block{ width:50px; height:50 ...

Vuejs components that have checkboxes already selected out of the box

Hey there, I'm facing a small issue. Whenever I click on the areas highlighted in the image, the checkbox on the left gets marked as well. Any idea why this might be happening? https://i.stack.imgur.com/nqFip.png <div class="form-check my-5&qu ...

Having trouble with changing the selected value in JQuery?

I'm attempting to use jQuery to set the select option, but I'm encountering an issue. It is setting the value properly, but the text is not being updated. I've experimented with .prop('selected',true), .attr('selected',t ...

Angular2: Leveraging click events to manage CSS classes on elements

I am currently developing a web app using Angular 2. I'm facing an issue where the active element should receive an extra CSS class when clicked, but adding the ":active" CSS attribute with a custom class doesn't work as expected. The ":focus" pr ...

Altering CSS attribute values using a random number generator

Is there a way to randomly change the animation-duration attribute in the following CSS code? I want it to range from 0 to 1. @keyframes blink { 50% { border-color: #ff0000; } } p{ animation-name: blink ; animation-duration: 0.1s ; animatio ...

Issues encountered with the functionality of face-api and tensorflow.js within the browser

I've been trying to execute this example in the browser Check out the example here Specifically looking at this code snippet <!DOCTYPE html> <html> ... (Contents of the code snippet) ... </body> </html> Unfortunately, I&apos ...

The animation-play-state is set to 'running', however, it refuses to start playing

I'm in the process of creating a landing page that includes CSS animations, such as fade-ins. Initially setting animation-play-state: "paused" in the CSS file, I later use jQuery to trigger the animation while scrolling through the page. While this s ...

Display or conceal elements in a v-for select input by leveraging the value of another input with Vue3

In my form, I have two dropdown select option fields generated using loops from predefined constants. One dropdown is for selecting different "sides" and the other for choosing various "caps". When a user selects "2-Sided" in the sides dropdown, I want t ...

Utilizing HTML snippets for AJAX integration

Let's dive in, I may be completely off track here. I am currently working with Wordpress. On a page I am creating an HTML select menu (Main Menu) with options that correspond to each page on the site. This menu is visible on the page. In addition, ...

Display/hide a div containing distinct content

Upon clicking an image in the carousel, a position: absolute; div should appear containing two different images and a form related to the initial picture clicked with a submit button. How can I implement a show/hide feature that displays unique content for ...

Error encountered when attempting to export a TypeScript class from an AngularJS module

In my application using Angular and TypeScript, I have encountered a scenario where I want to inherit a class from one module into another file: generics.ts: module app.generics{ export class BaseClass{ someMethod(): void{ alert(" ...

Is there a way to turn off Emmet's CSS Abbreviations feature in Sublime Text 2?

One thing I really enjoy is how Emmet can generate HTML using 'CSS-like' strings. However, I prefer not to use their CSS Abbreviations. For example, when I write the following line of CSS: li a| I expect to get a tab when I press 'TAB&apos ...

Dynamically inserting templates into directives

I've been attempting to dynamically add a template within my Angular directive. Following the guidance in this answer, I utilized the link function to compile the variable into an HTML element. However, despite my efforts, I haven't been success ...

Changing the image source when clicking on it and removing it can be done by using JavaScript

How can I add a class 'selected' to ".swiper-slide" when it is clicked? I also want to change the image src when svg-img1, 2, or 3 is clicked. However, I need the image to revert back to its default src when another swiper-slide is clicked. ...

Tips for populating class attributes from an Angular model

Suppose there is a Class Vehicle with the following properties: public id: number; public modelId: number; public modelName: string; Now consider we have an object that looks like this {id: 1, modelId: 1, modelName: "4"} What is the best way to assign e ...

Populate an AngularJS select dropdown with JSON data and automatically pre-select the specified value

I am currently dealing with 2 entities: project and project_types. Each project can have one or multiple project_types associated with it. Using ajax (ng-init), I am retrieving the project data (including its related project_types) and all available proje ...

Creating an array object in JavaScript is a straightforward process that involves using the array

Looking to achieve the following object list structure: myObj = {"foo":[1,2,3,4], "bar":[3,5,7,8]} Initial attempt was unsuccessful: var myObj = new Object(); myObj["foo"].push(1) myObj["foo"].push(2) #...etc Seeking guidance on the correct m ...

24-hour countdown tool featuring a visual progress bar

Currently, I am in the process of developing an application aimed at assisting individuals in either forming new habits or breaking old ones. In this application, I am looking to implement a countdown timer that ticks down daily; with the help of this help ...

The current version of 'buffer' is outdated. To resolve this issue, please upgrade to v4.9.2 or higher

Having some trouble integrating aws-amplify and aws-amplify-react modules into my application. After running: npm install --save aws-amplify aws-amplify-react I encountered multiple warning messages related to missing or deprecated dependencies. Althoug ...