Difficulty with Jquery's random selection of grid divs

I am working on a grid layout consisting of 9 divs nested in columns of three. The objective is that when the main grid (with ID #left) is clicked, two divs from the middle row (row="1") should have the class .show randomly applied to them. In the column where no class was applied, the div from the bottom row (row="2") should have the class .show applied instead. The image attached illustrates the possible random outcomes. It is important to note that the same outcome should never appear consecutively.

Included below is a snippet of the code I have written for this functionality. However, I am encountering issues with my index selection logic and have been unable to identify the root cause of the problem.

https://i.sstatic.net/EO24n.png

var obj = {
  bindEvents: function() {
    var _this = this;
    $('#left').on("click", $.proxy(_this.interaction, _this));
  },
  interaction: function() {
    var selector = this.randomGenerator(0, 3);
    console.log('selector = ' + selector());
    var $midRow = $('#left').find('div[row=1]');
    var $bottomRow = $('#left').find('div[row=2]');
            
    $midRow.removeClass('show');
    $bottomRow.removeClass('show');
    $midRow.not(':eq(' + selector() + ')').addClass('show');
    $bottomRow.eq(selector()).addClass('show');
  },
  randomGenerator: function(min, max) {
    var last;
    console.log('last = ' + last);

    return function () {
      var random;
      do {
        random = Math.floor(Math.random() * (max - min)) + min;
      } while (random === last);
        last = random;
        return random;
      };
    },
}
obj.bindEvents();
#left {
  display: flex;
}
div[row] {
  border: 1px solid black;
  width: 20px;
  background-color: yellow;
}
.show {
  background-color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left">
    <div col="0">
        <div row="0">0</div>
        <div row="1">1</div>
        <div row="2">2</div>
    </div>
    <div col="1">
        <div row="0">0</div>
        <div row="1">1</div>
        <div row="2">2</div>
    </div>
    <div col="2">
        <div row="0">0</div>
        <div row="1">1</div>
        <div row="2">2</div>
    </div>
</div>

Answer №1

You must remember to pass the necessary element to the functions you are using.
In this case, there is no automatic reference like this, so you have to provide it explicitly.

UPDATE
Keep in mind that each time you call the selector() function, a new number will be generated.

If you intend to use the same "number" in consecutive calls to .eq(), make sure to store the number in a variable after calling the function once.

Take note of the code modifications below.

var obj = {
  bindEvents: function(el) {  
    el.on("click", $.proxy(obj.interaction(el), el));   
  },
  interaction: function(el) {
    var selector = obj.randomGenerator(0, 3);  
    
    // Generate a number
    var number = selector();
    console.log('selector = ' + number);

    var $midRow = $('#left').find('div[row=1]');
    var $bottomRow = $('#left').find('div[row=2]');
            
    $midRow.removeClass('show');
    $bottomRow.removeClass('show');
    $midRow.not(':eq(' + number + ')').addClass('show');
    $bottomRow.eq(number).addClass('show');
  },
  randomGenerator: function(min, max) {
    var last;
    console.log('last = ' + last);

    return function () {
      var random;
      do {
        random = Math.floor(Math.random() * (max - min)) + min;
      } while (random === last);
        last = random;
        return random;
      };
    },
}
obj.bindEvents($("#left"));
#left {
  display: flex;
}
div[row] {
  border: 1px solid black;
  width: 20px;
  background-color: yellow;
}
.show {
  background-color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left">
    <div col="0">
        <div row="0">0</div>
        <div row="1">1</div>
        <div row="2">2</div>
    </div>
    <div col="1">
        <div row="0">0</div>
        <div row="1">1</div>
        <div row="2">2</div>
    </div>
    <div col="2">
        <div row="0">0</div>
        <div row="1">1</div>
        <div row="2">2</div>
    </div>
</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

The function auth.createUserWithEmailAndPassword is not recognized in the context of React

base.jsx: import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; const firebaseConfig = { config }; export const app = initializeApp(firebaseConfig); export const auth = getAuth(); Register.jsx ...

Uploading files with ExpressJS and AngularJS via a RESTful API

I'm a beginner when it comes to AngularJS and Node.js. My goal is to incorporate file (.pdf, .jpg, .doc) upload functionality using the REST API, AngularJS, and Express.js. Although I've looked at Use NodeJS to upload file in an API call for gu ...

CSS3 transition applied to a jQuery direction-aware hover effect

I'm encountering difficulties making direction-aware hover and css transitions function correctly. Specifically, I am attempting to create a grid of elements with front and back faces, and on hover, have a css transition that flips the element to disp ...

Error: When attempting to access the 'name' property of an undefined object, a TypeError is thrown. However, accessing another property on the same object does

Retrieving information from API. The fetched data looks like [{"_id":"someId","data":{"name":"someName", ...}}, ...] My state and fetching process are as follows: class Table extends React.Component { constructor() { super(); this.state = { ...

Presentation: Positioning Next Buttons Beside Slide Images While Maintaining Responsiveness

I am facing a challenge with my slideshow project. The slideshow consists of images and text on each slide, along with previous and next buttons that are aligned within the parent container. I am trying to align these buttons at the midpoint of each image ...

How can I toggle the visibility of stacked divs using jquery?

I am trying to create a specific effect with two divs. The goal is to display them one after the other, with the first fading in, then fading out, followed by the second div fading in and then fading out. $('[class^="flash"]').each(function(inde ...

Which is the better option for data storage: JSON files or MySQL database?

I am currently developing a project that utilizes the vis.js JavaScript framework to showcase a visual network of various categories. There are approximately 2000 categories available for selection, each with a substantial amount of associated data. I am ...

Tips for Preventing Ant Design from Overriding Existing CSS Styles

Currently, I am working on a ReactJS project. Initially, the entire project was designed using pure CSS. However, I decided to incorporate a small Antd component into my project. Following the provided instructions, I imported the component like this in on ...

Executing a script that has been inserted into the page post-loading

I'm facing an issue where the script tag at the bottom of my project is not being executed after adding new pages later on. Main const fetch = (url, call) => { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if ...

JavaScript tool for implementing sorting features on an HTML table

I am facing an issue with my AJAX-loaded table where I need sorting functionality implemented. Despite searching for various JavaScript plugins, none seem to work efficiently due to slow performance or errors. The structure of my HTML table is unique with ...

Is there a way to visualize the prototype chain of a JavaScript object?

Consider the following code snippet: function a() {} function b() {} b.prototype = new a(); var b1 = new b(); It can be observed that a has been incorporated into the prototype chain of b. This demonstrates that: b1 is an instance of b b1 is an instance ...

The issues of cross-origin domains arise when utilizing iframes with src links originating from the server side

Encountering a cross-origin domain issue, receiving the following error while working with an iframe: candidateInterviewCtrl.js:39 Uncaught SecurityError: Blocked a frame with origin "http://localhost:9000" from accessing a frame with origin "http://local ...

Removing one element from an array with mongoose

As a newcomer to web development, I am currently working on creating a todo app. Below is the schema and model that I have: const tdSchema = new mongoose.Schema({ category: { type: String, required: true, unique: true }, tds: { type: ...

Querying Firebase by the value of a child node

Here is how my structure looks like: 2017511 UcQefEaHJG6fteGsbsiaWjQ60d9Q62 value1: 50 value2: 1200 value3: "blabla" AcQefEaHJG6fteGsbsiaWjQ60d9Q62 value1: 55 value2: 2200 value3: "balabla" BcQefEaHJG6fteGsbsiaWjQ6 ...

Help! My express.js query is not functioning properly

I am facing an issue with a query in express.js. Citta_p and Citta_a are two arrays, and I need my query to return all the IDs for cities. However, it seems that only the last value is being returned, as if my cycle starts from var i = 1 and skips the valu ...

Reduce the number of divs on a webpage while incorporating animated transitions

I've been attempting to incorporate an animation on the width property for my div .panels. I've tried using transition-property in CSS and also with .animate() in jQuery, but unfortunately, it doesn't seem to be working. I also noticed that ...

Contrast 2 GET objects retrieved from separate controllers

I have 2 collections of data from different controllers. Data Collection 1 (Controller Name): [{id:1,"name":"jakov"},...] Data Collection 2 (Controller Nickname): [{id:1, "nickname" : "jandric", "nameId" :1, "title" : "master"},...] I send data from C ...

What factors determine when Angular automatically triggers a setTimeout function compared to another?

Sorry if this all seems a bit odd, but I'll do my best to explain the situation. We have been given access to a small service that provides a simple form UI which we collect results from using an event. We've successfully implemented this in two ...

the sizing issue with three div elements

I am attempting to create 3 parallel divs in HTML. The middle div should be exactly 960px wide and centered on the page, with the left and right divs positioned on either side. The minimum width of the page is set to 1024px. When the browser width exceed ...

Guide on displaying Solr Documents returned using the Jquery Autocomplete plugin

In my Spring MVC 4.X project with Solr integration for data indexing and querying, I am diving into the world of JQuery and JavaScript. While exploring, I came across a code snippet that directly queries the Solr URL from a JSP page. However, I believe tha ...