Alex Cory Alex Cory - 5 months ago 20
Javascript Question

JQuery works when pasted into console but not on page load

Why does this not work on page load, but when I paste the jquery into the console on my page it works.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Alex Cory</title>
<link rel="stylesheet" href="//">
<body id="page-top" data-spy="scroll" data-target=".navbar-custom">
<div id="root"></div>
<script src="src/app.js"></script>
<script src="//" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script src="//"></script>
<script src="//" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
$('.page-scroll a').bind('click', function(event) {
console.log('CLICKED BUTTON! ^_^');


Judging by how your webpage seems to be set up, I suspect you're injecting your content into the page from:

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

since there's no actual content in the code itself.

When this is the case, it's because when the page loads and $(document).ready() fires, $('.page-scroll a') returns null because it's not rendered into the DOM yet, to put it simply.

To solve this issue, you need to attach your event handler to an element that is going to be rendered into the page when it loads. The body tag is good for this example, and we want to listen for .page-scroll a to be clicked using jQuery's on method:

// We attach a click event listener to the body element
// and we try to track when .page-scroll a is clicked 
$('body').on('click', '.page-scroll a' function(event) {
  console.log('CLICKED BUTTON! ^_^');

This works because since the event handler is attached to the body, each time something is clicked on the web page, it checks to see if .page-scroll a is clicked, rather than before you were trying to attach an event handler to an element that didn't exist yet.