I'm trying to hide an element on click using the .hide() method. In the code below, I can hide object1 when I select it specifically by ID. I have the element stored in a variable but when I use hide() on the variable, it doesn't work. Why would the method not work when I use the variable, but work just fine when I select it specifically?
Here is the code:
<div id="object1">Object 1</div>
<div id="object2">Object 2</div>
<input type="button" id="button" />
<script>
$(document).ready(() => {
const object1 = $('#object1');
const object2 = $('#object2');
const button = $('button');
});
button.addEventListener("click", () => {
$('#object1').hide();
});
</script>
When I use the following code (replacing $('#object1') with its variable) the code doesn't execute.
$(document).ready(() => {
const object1 = $('#object1');
const object2 = $('#object2');
const button = $('button');
});
button.addEventListener("click", () => {
object1.hide();
});
Am I doing something wrong, or is there limitations in JS surrounding this?
EDIT:
Even after moving the event listener into the document ready, the code still isn't executing. Here is the most recent code
<div id="object1">Object 1</div>
<div id="object2">Object 2</div>
<input type="button" id="button" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(() => {
const object1 = $('#object1');
const object2 = $('#object2');
const button = $('#button');
button.addEventListener("click", () => {
object1.hide();
});
});
</script>
This is a closure problem. The scope of your click function does not know about object1. You have two options:
Option 1: Move your event listener inside the document ready. I would go for this option personally since it avoids polutting the window object
$(document).ready(() => {
const object1 = $('#object1');
const object2 = $('#object2');
const button = $('button');
button.addEventListener("click", () => {
object1.hide();
});
});
Option 2: Move your vars outside so all methods have them available.
let object1 = null;
let object2 = null;
$(document).ready(() => {
object1 = $('#object1');
object2 = $('#object2');
const button = $('button');
});
button.addEventListener("click", () => {
object1.hide();
});