Using JQuery to enhance web functionality with the combination of HTML and CSS styling

I am trying to achieve a specific effect on my website. In the folder, I have the following files:

  • index.html
  • style.css
  • script.js

My goal is to make the navigation with id #menu stick to the top of the page when I scroll, similar to how it works on . However, I am only familiar with html and css.

Here is a snippet from my index.html file:

<!DOCTYPE html>
<title>Title</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<header id="main-header">
  <h1>Title</h1>
  <h2>Slogan</h2>
</header>
<nav id="menu">
</nav>
<section id="main-section">
</section>
<footer id="main-footer">
  © 2014 Copyright
</footer>

This is a portion of my style.css file:

* {
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  font-family: sans-serif;
}

body {
  margin: 0;
} 

h1 {
  font-size: 3em;
  margin: 0;
}

h2 {
  font-size: 2em;
  margin: 0;
}

#main-header {
  background: #08c;
  color: #fff;
  height: 10em;
  padding: 2em;
  text-align: center;
}
// More CSS styling here...

The script.js file contains the following code:

$(document).ready(function() {
  var menu = $("#menu");
  var pos = menu.position();

  $(window).scroll(function() {
    if ($(window).scrollTop() >= pos.top) {
      menu.addClass("sticky");
    } else {
      menu.removeClass("sticky"); 
    }
  });
});

Answer №1

  1. The script.js file you're using contains jQuery code, but the jQuery library is not included.
  2. Your HTML code is formatted incorrectly.

Here is a revised version of your code that should work:

<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<body>
<header id="main-header">
  <h1>Title</h1>
  <h2>Slogan</h2>
</header>
<nav id="menu">
</nav>
<section id="main-section">
</section>
<footer id="main-footer">
  © 2014 Copyright
</footer>

<script src="script.js"></script>
</body>
</html>

Changes made to improve functionality:

  • Added body and head tags,
  • Moved the script tag that includes jQuery to the head section for better practice (can be loaded locally as well),
  • Repositioned the script tag at the end of the body for faster page rendering.

You mentioned that the script wasn't working and no errors were showing in the developer tools. In Chrome's console tab, you may see "Uncaught ReferenceError: $ is not defined".

For future reference, ensure to include the necessary code components earlier in your document.

Previous recommendation:

<script src="script.js" type="application/javascript"></script>

Note to downvoters: The 'type' attribute is required in HTML 4.x, though it is optional in HTML5.

Answer №2

By including the following code in an HTML document:

<script src="script.js"></script>

You establish a connection wherein the browser loads and interprets the JavaScript file accordingly.

This same principle applies to CSS files as well. When both are present on the same page, they can interact with each other (allowing you to manipulate CSS classes through JavaScript).

Answer №3

Here is a demonstration provided by a novice on how to incorporate functionality into your javascript file.
When integrating files into your html source, it is essential to adhere to the html syntax.

<script src="script.js">
/**
 * You can even include additional code here
 */
</script>

Make sure to stick to this format.
Similarly, when adding the css file, remember to utilize html syntax.

<link href="style.css" rel="stylesheet" type="text/css">

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

How to Solve the Frustrating Problem of Ensuring Page Content 100% Height of Document

Currently, I am in the process of creating the second version of my new web app called Trekeffect. My main goal is to ensure that the interface content takes up 100% of the page's height. However, despite my best efforts, I haven't been successfu ...

What is the process for inserting an SVG object into an HTML document?

Currently, I am experimenting with d3.js examples to create visual graphs. Here is the link for reference. Below is the snippet where I've implemented the LineChart function to construct the graph, with Django as the backend. {% load static %} < ...

Unable to add personalized repository

Looking to implement a request-scoped cache for my repositories, inspired by Hibernate's first-level-cache. I have some ideas on how to achieve this and integrate it with typeorm-transactional-cls-hooked. For now, I've created a basic provider s ...

The Role of AI in Gaming

I am currently developing a car racing game using THREE.js. I am inquiring about how to incorporate Artificial Intelligence into the enemy cars so that they can actively search for and target the player. Can you provide insight into the algorithms typica ...

Gather all possible routes within the JSON structure

I am faced with a JavaScript object that contains various data: { "gender": "man", "jobinfo": { "type": "teacher" }, "children": [ { "name": & ...

Problem with Bootstrap 5 dropdown menu: Functional on main page, but failing on subpages

As a beginner with Bootstrap, I recently attempted to integrate a dropdown menu into my website by following the Bootstrap documentation (version 5.1) for guidance. While the dropdown menu functions correctly on the homepage, it fails to work properly on ...

A guide on displaying varying values of a single item across different dates in react.js

Here is an example of an array: array = [ { "id": 1, "date": { "id": 1, "name": "202001" }, "item": { "id": 1, "name": "I1" ...

Create customized validation decorators in class-validator for TypeScript by overriding the `validationOptions` within the `validator` method

Take a look at the example provided in section Custom validation decorators: // Defining a decorator import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator'; export function IsLongerThan(property: string, va ...

Steps for importing a Java project into Eclipse and configuring it to run on a Tomcat server

I need guidance on how to import an external project into a Tomcat server in order to view the output in a browser. The project is an online banking system developed using JSP, AJAX, and JavaScript. ...

Tips for aligning a `img` element with absolute positioning within a `div` element while preserving its original aspect ratio

Here is an image along with its corresponding CSS: .containerImg { height: 420px; margin-top: 0; position: relative; width: 100%; } .img { margin: 0 auto; position: absolute; /*I cannot remove the position:absolute unfort ...

Tips for successfully retrieving a variable from a function triggered by onreadystatechange=function()

Combining the ajax technique with php, I'm looking to extract the return variable from the function called by onreadystatechange. A java function triggers a call to a php script upon submission, which then validates certain data in the database and r ...

Center the ordered list using margin:auto

Does anyone know how to properly set margin-auto on an ordered list? I'm having trouble with it in a complex setup. Unfortunately, I can't create a fiddle for demonstration purposes, but you can see the problem here. I want the ordered list on t ...

Is there a way to export a specific portion of a destructuring assignment?

const { a, ...rest } = { a: 1, b: 2, c: 3 }; If I want to export only the rest object in TypeScript, how can I achieve that? ...

Strategies for positioning a fixed div at the bottom of another div

I'm in the process of creating a digital restaurant menu... I decided to format it as a popup, situated within a fixed container on top of a gray transparent overlay. However, with a large number of dishes, the content exceeds the size of the containe ...

Vuetify displaying incorrectly following deployment

After creating a spa with vue.js for the frontend, I utilized the vuetify library for various components and layout. While everything looked great locally, upon deploying to Azure, all vuetify styling seemed to disappear. My custom css was still applying ...

NodeJS CORS functionality failing to function properly in the Google Chrome browser

In my nodejs script, I have implemented CORS as shown below: var express = require('express') , cors = require('cors') , app = express(); app.use(cors()); To fetch JSON data from another domain, I am using an AJAX request. While ...

Adding a timestamp to the src URL in HTML: A step-by-step guide

Looking for a way to implement cache busting in my index.html file. Take a look at the code snippet below: <body> <app-root></app-root> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="&l ...

Encountering the "React Hook useEffect missing dependency" warning for a state variable that does not actually need to be included in the dependency array

My eslint is throwing an error for react-hooks/exhaustive-deps. I believe my code is correct as the function should only execute when there is a change in the pathname: const pathname = usePathname(); useEffect(() => { setNavigation( navig ...

What is the proper way to specify the type for a <video> element reference in React when utilizing Typescript?

I have been experimenting with controlling the play/pause state of a video in React.js using ref's. My code functions correctly but I am encountering tslint errors that I am currently trying to diagnose: function App() { const playVideo = (event:a ...

Issues with lazy loading in swiper.js when trying to display multiple images per slide

I recently tried using swiper.js and had success with the lazy loading demo. However, I encountered an issue where only one image per slide was showing up, despite wanting to display 4 images per slide. <div class="swiper-container"> <div cla ...