-3

I want to switch once a button is pressed. This is the code. It would not be for something so simple, but I can't even get this to work.

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Test</title>
    <script src="app.js"></script>
    <link rel="stylesheet" href="style.css">
</head>

<body>

    

    <div class="page-section page-1 active"><h1>I'm page 1</h1></div>
    <div class="page-section page-2"><h1>I'm page 2</h1></div>
    
    <button class="link link-1">Page 1 link</button>
    <button class="link link-2">Page 2 link</button>
</body>

</html>

CSS


.page-section {
  width: 200px;
  height: 200px;
   display: none;
}
.page-1 {
  background-color: blue;
}
.page-2 {
  background-color: red;
}
.page-section.active {
    display: block;
}

JS


function pageActivator(page) {
    $('.page-section').removeClass('active');
    page.addClass('active');
}

$('.link').click(function() {
    var pageNum = parseInt($(this).attr('class').match(/\d+/g)[0]);
    pageActivator($('.page-' + pageNum));
});

This is the codepen, on the website it works, while locally it doesn't I have no idea why. I really don't understand because the code is the same from the codepen, maybe I am missing something on the HTML file? Even if the .js file is correctly connected, I have verified it. And the CSS file too.

  • You're loading `app.js` in the DOM *before* any elements matching the selector `.link` are loaded into the DOM. Consequently, your `.click()` handler will not be attached to your elements properly. Move your `` node to the end of your ``. – esqew Feb 16 '22 at 21:25
  • 2
    Duplicate of [Attaching click event to a JQuery object not yet added to the DOM](https://stackoverflow.com/questions/10920355/attaching-click-event-to-a-jquery-object-not-yet-added-to-the-dom) – esqew Feb 16 '22 at 21:26

1 Answers1

0

You use JQuery codes but you did not call JQuery library. Do the following:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Test</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="app.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
RSD
  • 87
  • 9