After a refresh, jQuery's mousenter event is not functioning

I am currently working on a fun project called Etch-a-Sketch for The Odin Project, and I have a jquery grid that can be redrawn with the click of a button.

Initially, the grid allows the user to choose the size and then draw on it using .mouseenter. However, after clicking the reset button, the drawing functionality seems to break. I'm puzzled as to what might be causing this issue.

To view the project in action, you can check out my jsfiddle here: https://jsfiddle.net/davidtaylorjr/cLcbxmnb/14/

Here is a snippet of the HTML:

<div class="grid_controls">
   <button class="clear button">Clear and Redraw</button>
</div>
<div class="container"></div>

And the CSS:

.grid_controls {
  text-align: center;
}

.button {
  position: absolute;
  top: 50%;
}

.box {
    margin:0;
    border:1px solid lightblue;
    box-sizing:border-box;
    float:left;
}

.container{
    padding:5px;
}

/* Rest of the CSS styling */

Lastly, here is the Javascript part of the project:

$(function(){

    // Functions and event handlers

})();

Answer №1

To properly handle events for dynamically added elements, it is recommended to utilize the event delegation syntax provided by the .on() method

$(document).on('mouseenter', ".box", function() {
    $(this).addClass('black');
});

Check out this jsFiddle example

Answer №2

When you redraw the box, the <code>mouseenter
event will not be triggered anymore.

To solve this issue, you can use the .container to delegate the event.

$(".container").on('mouseenter', '.box', function() {
  $(this).addClass('black');
});

For more information, you can refer to

.on( events [, selector ] [, data ], handler )

Answer №3

Issue arises when the event is not inserted into the DOM during the redraw process. Insert this

//Activate drawing boxes on hover
$(".box").mouseenter(function() {
  $(this).addClass('black');
});

within the drawboxes function

     function drawBoxes(){
            var gridWidthInBoxes = prompt("Enter the width of the grid in boxes?");
            //Clear existing boxes and redraw
            $('.box').remove();
            for(var i = 0; i < (gridWidthInBoxes * gridWidthInBoxes) ; i++){
                $(".container").append("<div class='box'></div>");
            }
            //Apply styles to the newly drawn boxes
            restyle(gridWidthInBoxes);
//inserted here
        $(".box").mouseenter(function() {
          $(this).addClass('black');
        });
    }

Answer №4

Give this a try, it can be beneficial for you.

  $(function() {
    //Calling the original function
    drawBoxes();

    //Drawing .box div elements
    function drawBoxes() {
      var gridWidthInBoxes = prompt("Enter the width of the grid in boxes:");
      //Removing existing boxes and redrawing
      //$('.box').remove();
      $(".container").empty();
      for (var i = 0; i < (gridWidthInBoxes * gridWidthInBoxes); i++) {
        $(".container").append("<div class='box'></div>");
      }
      //Restyling the boxes after drawing
      restyle(gridWidthInBoxes);
    }

    //Styling .box divs with the correct width
    function restyle(numberofBoxes) {
      //Setting width and height css values for '.box' divs
      $('.box').css('width', (100 / numberofBoxes) + '%');
      $('.box').css('height', (100 / numberofBoxes) + '%');
    }

    //Button click event handler
    $("button").on('click', function() {
      drawBoxes();
    });

    //Hover effect to draw boxes
    $(".container").on('mouseenter', '.box', function() {
      $(this).addClass('black');
    });

  });
.grid_controls {
  text-align: center;
}
.button {
  position: absolute;
  top: 50%;
}
.box {
  margin: 0;
  border: 1px solid lightblue;
  box-sizing: border-box;
  float: left;
}
.container {
  padding: 5px;
}
/*=================
General
=================*/

body {
  background: white;
}
/*=================
Sketchpad Holder
=================*/

.container {
  width: 500px;
  height: 400px;
  background-color: none;
  overflow: hidden;
  margin: auto;
  position: relative;
  top: 20px;
}
.box {
  background: white;
  position: relative;
}
.clear {
  position: relative;
  margin: auto;
  text-align: center;
}
.box.black {
  background-color: #000;
}
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<div class="grid_controls">

  <button class="clear button">Clear and Redraw</button>
</div>
<div class="container">
</div>

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

Assigning active classes based on the href attributes of child <a> tags

I've created a navigation structure as follows: <ul class="page-sidebar-menu"> <li class="menu"> <a href=""> <span class="title">Menu Item</span> <span class="arrow"></span> < ...

Utilize JavaScript to parse HTML content retrieved through AJAX requests

My current project involves writing JavaScript code, specifically a Chrome extension, that needs to: Retrieve the contents of a web page using AJAX. Extract specific content from the page by identifying certain elements within the HTML string and retriev ...

What is the best way to retrieve data from PHP and format it into JSON for use in my jQuery script?

I need help formatting the data returned to jQuery from a query. The specific format I want is: var externalDataRetrievedFromServer = [ { name: 'Bartek', age: 34 }, { name: 'John', age: 27 }, { name: 'Elizabeth', ...

I am having trouble printing because of document.write

Whenever I use javascript to create a document with document.write I include an iframe element then I try to print the contents using iframe.print() but nothing happens - no error message and no print dialog box. How can I successfully initiate a print ...

Tips for showcasing elements individually in JavaScript when a button is clicked and halting on a random element

I have some names stored in h3 tags. I want to highlight one name at a time when I click a button, stopping at a random name. <div class="all-names"> <h3 class="name-one"><span class="line">Name ...

Error: Attempting to access the 'url' property of an undefined variable, despite specifically checking for its undefined status

Within my React application, I am utilizing the following state: const [functions, setFunctions] = useState([{}]); I have created a test to check if a specific property is undefined: if (typeof functions[functionCount].url !== "undefined") { ...

Edit: "Submit a binary file with just JavaScript"

I am currently developing a Chrome application that utilizes the HTML5 Filesystem API to enable users to import and synchronize files. A challenge I'm facing is when attempting to sync image files, as they appear to become corrupted during the upload ...

The navigation bar extends beyond the container

First time diving into bootstrap and struggling with my items overflowing the container. Here's a snippet of my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equi ...

Making an Angular 6 HTTP GET call using HTTP-Basic authentication

When attempting to access a URL that requires Basic Authentication, and returns JSON data, what is the proper way to include my username and password in the following HTTP request? private postsURL = "https://jsonExample/posts"; getPosts(): Observable& ...

pass the HTML output back to Python

I am currently working on a local website using Python to create a button that will open the door to my room from my phone through a Raspberry Pi. I have already created a Python program that successfully opens the door, but now I am trying to implement an ...

Tips for Showing Certain Slides When the Page Loads

When using jQuery filter effects to organize div slides on a page, I encountered an issue where all the divs containing different slides are displayed on page load instead of just the default chosen ['active'] div. The filter effect itself is fun ...

What are some ways to implement querySelectorAll in conjunction with htmx?

I'm currently using htmx, an amazing library with a small issue that I'm struggling to resolve. htmx utilizes querySelector to find elements for swapping or updating, for example with hx-swap="...", hx-target="...". How can I use querySelectorAll ...

does not output any console log statements

I am attempting to showcase the values of checkboxes on the console, however, it is not working. <input type="checkbox" id="id_price" value="1" onclick="display_img()">Under £200<br> <input type="checkbox" id="id_pr ...

Why is the 'a' element not clickable after the AJAX complete function has executed in JavaScript?

I have a small question regarding my use of AJAX. Everything is working fine, but after the AJAX request completes, I am trying to change the element attributes such as backgroundImage dynamically. Although this process works correctly, the element that wa ...

Creating a Click Counter with jQuery 2.0.1/2.0.2: A Step-by-Step Guide

Currently in the process of creating a fundraising webpage for charity, I have chosen to display an animated rabbit making its way Around The World. My progress so far includes a non-looping gif that plays on click, with a limitation on how often it can b ...

Express.js does not display console.log messages while routing

Just starting to explore Express and its middleware functions. var express = require('express'); var app = express(); app.get('/', function(req, res) { res.send('id: ' + req.params.id + ' and name: ' + req.param ...

Exploring the power of tRPC for creating dynamic routes in NextJs

Recently, I embarked on a new project using the complete t3 stack (Nextjs, prisma, tailwind, tRPC), and encountered a minor hiccup. To provide some context, within my database, I have an "artists" table containing fields such as name, email, address, id, ...

ReactJS integration issue with Material Design Lite (import/require problem)

I am currently integrating Google's Material Design Lite with ReactJS. Specifically, I am utilizing the Spinner Loading and Text Field components from the MDL library. However, I am encountering an issue when switching routes using React Router. The ...

Is there a way to make a selected option stay selected in vue.js 2?

Here is the structure of my Vue component : <template> <select class="form-control" v-model="selected" :required @change="changeLocation"> <option :selected>Choose Province</option> <option v-for="option in o ...

Creating a color icon for StackExchange using HTML

I am currently working on building my personal website. I am looking to include a link to my Stack Exchange profile on my site using the Stack Exchange icon. However, the icons available in Font Awesome are grayscale and not colored like other icons such a ...