The code runs perfectly on CodePen, but it's not functioning properly on my website

After successfully resolving an issue on Codepen, I encountered a problem when transferring the JavaScript/JQuery code to my website. It seems that none of the JavaScript functionalities are working properly. Here is the link to the functional Codepen: http://codepen.io/anon/pen/aOXMLR

Below is the code snippet:

HTML:

<html>
<link rel="stylesheet" type="text/css" href="main.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="function.js"></script>
<script type="text/javascript" src="jquery.waypoints.min.js"></script>

</script>


<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,900' rel='stylesheet' type='text/css'>

<head>
  <title>Joseph Cooper</title>
</head>

<body>

  <header id="home">

      <nav id="nav-wrap">
        <ul id="nav" class="nav">
          <li class="current"><a class="page" href="#home">Home</a></li>
          <li><a class="page" href="#about">About</a></li>
          <li><a class="page" href="#portfolio">Portfolio</a></li>
          <li><a class="page" href="#scrapbook">Scrapbook</a></li>
          <li><a class="page" href="#contact">Contact</a></li>
        </ul>
      </nav>

      <div class="header-content">
        <img id="logo" src="img/logo.png" alt="logo" height="200px" width="200px">
        <h3>Joseph Cooper</h3>
        <h3>Graphic Designer</h3>
        <p> 10.03.97 </p>
      </div>

    <a href="#about"><img id ="down" src="img/down.png" height="42px" width="42px"></a>

  </header>

<section id="about">
    <h3> About Me </h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci aperiam esse eum nam nobis nulla placeat quaerat quia sequi velit. A aut delectus, eos excepturi harum itaque maxime natus voluptatem.</p>
</section>

<section id="portfolio">
    <h3>Portfolio </h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci aperiam esse eum nam nobis nulla placeat quaerat quia sequi velit. A aut delectus, eos excepturi harum itaque maxime natus voluptatem.</p>
</section>

<section id="scrapbook">
    <h3>Portfolio </h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci aperiam esse eum nam nobis nulla placeat quaerat quia sequi velit. A aut delectus, eos excepturi harum itaque maxime natus voluptatem.</p>
</section>

  <section id="contact">
    <h3>Portfolio </h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci aperiam esse eum nam nobis nulla placeat quaerat quia sequi velit. A aut delectus, eos excepturi harum itaque maxime natus voluptatem.</p>
</section>

</body>
</html>

CSS:

    // when we scroll down the window, do this:
$(window).scroll(function(){

  //Getting the scroll percentage
  var windowHeight = $(window).height();
  var scrollHeight = $(window).scrollTop();
  var scrollPercentage =  (scrollHeight / windowHeight);
  console.log(scrollPercentage);

  // if we have scrolled past 200, add the alternate class to nav bar
  if(scrollPercentage > 1) {
    $('.nav').addClass('scrolling');
  } else {
    $('.nav').removeClass('scrolling');
  }

});

$('a[href*=#]:not([href=#])').click(function() {
  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
    if (target.length) {
      $('html,body').animate({
        scrollTop: target.offset().top - 80
      }, 1000);
      return false;
    }
  }
}); // code courtesy of CSS-Tricks

// apply the class of nav-active to the current nav link
$('a').on('click', function(e) {
  e.preventDefault();
});


// get an array of 'href' of each a tag

var navLink = $('ul.nav a');
console.log(navLink);
var aArray = [];

for(var i = 0; i < navLink.length; i++) {
  console.log(i);
  var aChild = navLink[i];
  var navArray = $(aChild).attr('href');
  console.log(navArray);
  aArray.push(navArray);
  console.log(aArray);
  var selector = aArray.join(" , ");
  console.log(selector);
}

$(window).scroll(function(){
  var scrollTop = $(window).scrollTop();
  var tops = [];

  $(selector).each(function(){
    var top = $(this).position().top -90;
    if(scrollTop > top) {
      var id = $(this).attr('id');
      $('.current').removeClass('current');
      $('a[href="#'+id+'"]').parent().addClass('current');
    }
    tops.push(top);
  });

});

Answer №1

The reason for this issue is that the elements you are trying to access do not exist on the page when the script is executed. One solution is to reposition the script tag at the end of the body:

  <script type="text/javascript" src="function.js"></script>
</body>

Alternatively, you can enclose the script content within the document.ready event:

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

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 possible to have a PHP variable embedded within an HTML link tag?

<?php $message = ' <a href="' . $link . '">here</a> '; ?> My goal is to include a clickable link in the $message variable for use in the mail() function. However, despite setting $link with the desired link string, it ...

Certain font sizes are causing an unexpected scrolling issue on single-line text

While working on a page, I noticed some elements had a 1px difference between scrollHeight and offsetHeight. This led me to investigate further. Check out the codepen example here HTML: <div>Text</div> CSS: div { font-size: 17px overfl ...

Is there a way to make a trio of buttons arranged in a flex column slide out to the left when hovered over using flexbox?

access the code example here .container { display: flex; flex-direction: column; border: 2px solid blue; } .mainCont { display: flex; background-color: #f2f2f2; min-height: 5em; justify-content: space-between; } .btn-group { display: f ...

Arranging React Bootstrap columns in a way that the column on the right appears above the column on the left

Is there a way to use React Bootstrap to create a layout with two columns side by side, and have the column on the right stack on top of the column on the left when the screen size is reduced? Check out the code snippet below: import "./styles.css&qu ...

unable to retrieve the chosen item from the dropdown menu

How can I retrieve the value of the selected item from a dropdown menu without getting an undefined error? You can find my code on Jsfiddle. Can anyone spot what might be causing this issue? <select class="ddl_status" id="status_ddl_20" style="display ...

Is it guaranteed that my callbacks will be executed sequentially and in order when iterating with a for loop in Node.js?

Sorry for the vague title, but I often encounter this issue and wonder about the best approach to handle it: I have an array or list that I want to iterate through and call methods with callbacks. Will all the callbacks be executed? And will they be done ...

Retrieving information from JSON files using AngularJS

Here is a JSON object example: [ { "user": "A220", "shorttext": "shanghai", "reportedBy": "S,A", "questions": " [{\"question\":\"Q1\",\"is_mand\":\"0\",\"type\":\"text\",\"a ...

Create a scenario where the text is placed within a set of <td></td> tags and allow it to overflow in an HTML document

Is there a way to center-align text and have it overflow the HTML cell if it's too long? Take a look at the image below for reference: https://i.sstatic.net/pnHid.png ...

Issue with bootstrap: When multiple svg tags are added to my navbar, it causes the container content to be deleted

Utilizing the Jumbotron Example from Bootstrap Examples has led to a peculiar issue when adding multiple icons to the navbar. After inserting anything following the first icon, a significant portion of the "container" class mysteriously disappears, as if i ...

Issues arising from the use of $.post

Currently, I am attempting to add some data into an SQL database. This is the code I am using: <input type="text" name="message" id="message" /> <input type="image" src="boca.png" onClick="send();" /> to retrieve the value inputted by the u ...

Dialogue box closes automatically within a dropdown menu

I am using shadcn in my next.js 13 project and I want to implement a dropdown feature that allows users to edit or delete an entry. However, when the user clicks on "delete", the dialog pops up for only about 0.5 seconds before closing along with the dropd ...

Is it possible for a while loop to display just one row?

<?php include 'db.php'; $sql_locations = "SELECT * FROM location"; $result = mysqli_query($conn,$sql_locations); $count = mysqli_num_rows($result); $markers = array(); while($row = mysqli_fetch_array ...

Determining the precise mouse location within child elements regardless of zoom level, scrolling, or dimension changes

My goal is to accurately determine mouse coordinates within the page elements. To see the code in action, please visit: http://jsfiddle.net/t8w9k6gu/ $('#p1, #p2, #p3').on('click mousemove touchmove', function(ev){ var target = ...

Whenever I refresh my website after deployment, I encounter an empty error using the MERN stack

Here is a question I previously posted: How can I properly use the res.sendFile for my MERN APP, as I encounter an error every time I refresh, and it was resolved there. I encountered a similar issue here, even after following the same steps that worked b ...

Ways to incorporate margins into text on PDF pages produced by Puppeteer without altering the background color

I am currently using puppeteer to generate PDFs that contain dynamic content. My goal is to include margins/padding above and below the text on consecutive pages. Unfortunately, when I try to add margins with the property margin: { top: "1cm", bottom: "1 ...

What could be causing the unexpected display of my Bootstrap 4 card headers?

I am currently in the process of upgrading a website from Bootstrap 4 Alpha 6 to Bootstrap 4 Beta 1. Within my cards, there is an icon accompanied by some right-aligned text. In the Alpha version, my cards appeared exactly as I wanted them to: +---------- ...

Applying a dynamic translate3d transformation on the ::after element using CSS3

My current challenge involves manipulating a pseudo ::after element using translate3d If I hardcode the values, it's straightforward: div::after { ... transform: translate3d(40px, 40px, 0); } Now, I want to dynamically set the value for the ...

Node's getRandomValues() function is throwing an "expected Uint8Array" error

Currently, I am experimenting with the getRandomValues() function to enhance an encryption REST API that I am developing for practice. My server is using Node, which means I do not have access to a window object containing the crypto object normally housin ...

Use the .replace() method to eliminate all content on the page except for the table

Extracting a table from a page that has been loaded through .ajax() in queue.htm has proven to be challenging. I am attempting to utilize .replace(regex) in order to isolate the specific table needed, but the process is unfamiliar to me. $j.ajax({ ...

Flask and jQuery combine forces to make a dynamically generated HTML table vanish in an instant

I am currently utilizing Flask (Flask API link) to develop a basic website that takes an 'order_id' and interacts with a MySQL database (MYSQL - Python API link) in the backend to display the associated items for that order_id in a table. While ...