A function that listens for the onmouseover event and updates the image source of an HTML img element

I have created a function that positions my objects based on the array they are assigned to.

For example, if they are in players[0], they will be placed in one position, and if they are in players[1], they will be placed elsewhere. The X and Y values are just placeholders for actual pixel values, which can vary significantly.

This function also takes a flag as a parameter to determine whether the source continues to the same location or changes to another source. Everything is functioning correctly.

function putHands(flag){
  let show;
  if(flag == true) show= true;
  else show = false;
  for(let i = 0; i < 4; i++){              
    for(let j = 0; j < 13; j++){
      if(i == 0 || i == 1 || i == 2 || i == 3){
        players[i][j].style.left = X;
        players[i][j].style.top = Y;
      }
      if(show == true)
        players[i][j].src = '../images/c'+players[i][j].id+'.gif';
    }
  }
}

Now, I want to include an event listener that changes the src of each object when hovered over. However, my attempts have resulted in an error message whenever I move the mouse over the objects:

Uncaught TypeError: Cannot read property '13' of undefined

Answer №1

To easily refer to the bound element, simply use this.

players[i][j].addEventListener('mouseover', function() {
  this.src = '../images/c'+this.id+'.gif';
});

If not, you'll be using the constantly changing variables i and j within the loop, resulting in unexpected values when the handler is triggered.

In essence, within the assigned handlers, it would end up being...

players[4][13]

...which falls outside of the specified range and is clearly not your intended result.

If you require i and j for other purposes, you can either directly add them to the element itself (if that's acceptable), or establish a new variable scope by creating another function in each iteration of the loop, passing i and j to it, and defining the handler within that scope.


Furthermore, since your function remains consistent across elements now, consider utilizing a single function instead of generating multiple ones in a loop.

function handler() {
   this.src = '../images/c'+this.id+'.gif';
}

function putHands(flag){
  show = !!flag;
  for(var i = 0; i < 4; i++){              
    for(var j = 0; j < 13; j++){
      // ...your code...

      players[i][j].addEventListener('mouseover', handler);
    }
  }
}

This way, one function is efficiently reused for all elements.


Lastly, slightly tangential, but this...

show = !!flag;

can replace this block of code:

if(flag == true) show= true;
else show = false;

It's worth noting that technically they are different due to the evaluation of == not just being based on truthy/falsey conditions. If the specific behavior of == is needed, the following can be used:

show = flag == true;

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

React state update not triggering a component re-render

I've been attempting to toggle the visibility of a div by clicking on another div, but I'm encountering an issue. The div becomes invisible on the first click only if it was visible initially. After that, it remains invisible and does not update. ...

Navigate to the editing page with Thymeleaf in the spring framework, where the model attribute is passed

My goal is to redirect the request to the edit page if the server response status is failed. The updated code below provides more clarity with changed variable names and IDs for security reasons. Controller: @Controller @RequestMapping("abc") public clas ...

What is the best way to highlight selected navigation links?

Recently, I implemented a fixed navigation bar with relevant links on a website. The navbar includes a jquery script for smooth scrolling when clicked. However, I am struggling to add a selected class to the clicked link. Despite trying various solutions f ...

Adding hue to the portion of text following a JavaScript split() operation

I need assistance in printing the text entered in a textarea with different colors. I am separating the string using the split() method, which works fine. However, I now want to print the substrings in the textarea with colors. How can this be achieved? & ...

Utilizing inline styles with the asset pipeline feature in Rails

<%= link_to root_path do %> <div class=""> <div style="background-image:<%= image_tag " image1.png "%>"> </div> <div> <h2>Title</h2> <p>Paragraph</p> </div& ...

Include a quantity dropdown menu on the cart page of your Shopify store's debut theme

Hey there! I'm currently customizing the Shopify Debut theme and I'm trying to incorporate a quantity selector as a dropdown on the cart page. Unfortunately, I'm encountering some issues with this implementation. I've managed to succes ...

Steps to Activate a Hyperlink for Opening a Modal Dialogue Box and Allowing it to Open in a New Tab Simultaneously

I am currently working on a website project. Within the website, there is a hyperlink labeled "View Page". The intention is for this link to open the linked page in a modal dialog upon being clicked. Below is the code snippet that I have used to achieve t ...

Integrating React js with Layout.cshtml: Mastering the Fusion of React Routing and ASP.NET MVC Routing

My current project involves an ASP.NET MVC core application with the View written in cshtml. The routing follows the conventional asp.net mvc routing pattern. However, I've recently implemented a new module using React JS. Now, I'm faced with the ...

delete the initial background color assigned to the button

The "ADD TO CART" and "save design" buttons are currently displaying as shown in the image below. I would like to make the "SAVE DESIGN" button look similar to the "ADD TO CART" button, meaning I want to remove the background-color and dot symbol. Code ...

Utilizing data attributes to configure jQuery plugin settings

Having trouble assigning options to an array value in a jQuery plugin using data attributes. When referencing the data attribute with a class selector: $('.tm-input').tagsManager( { prefilled: $('.tm-input').data('loa ...

Sending AJAX request within a Twitter Bootstrap modal in Symfony2

After exhausting countless Google and StackOverflow search results, I have come to the conclusion that seeking help is my best option. I am currently developing a Symfony2 application. In every view of my app, I have integrated a Twitter Bootstrap modal e ...

Node JS does not receive a response from JQuery Ajax

I have developed a form on the client side which includes: <html> <body> <script> $(document).ready(function() { $.ajax({ url: "Search.html", type: "POST", dataType : "json", s ...

Is there a way to modify the background hue of an upward facing triangle when a submenu is hovered over?

Access the Code on Fiddle #nav .submenu:before { content:""; position: absolute; width: 0; height: 0; border-bottom: 22px solid #b29600; border-left: 11px solid transparent; border-right: 11px solid transparent; margin: -12px ...

Steps for navigating to a different page by clicking on a gridview row

Currently, I am utilizing a grid view on my webpage. My specific request is that upon clicking on any row within the grid, it should redirect to a separate page where all the details of the selected row will be displayed. Appreciate your assistance! ...

AJAX requests sent from different origins to AWS S3 may encounter CORS errors on occasion

My current objective is to access publicly available files stored in S3. The CORS configuration for my S3 setup is as follows: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> < ...

Expanding the functionality of Element.prototype, problem related to anchor

Consider the following code: A JavaScript (JS) Snippet Element.prototype.changeInnerText = function(str) { this.textContent = str; return this; } let divElement = document.createElement('div').changeInnerText('new div text'); / ...

Is there a way to use javascript to ensure that CSS variables stick even when overwritten by onclick events?

I have successfully implemented a method to change CSS variables using advice found here. However, I am running into an issue where the changes do not persist. After clicking on a navigation link, the styles momentarily switch to the new values but quickly ...

Is there a way to position the icon in the top left corner within the image using Vue and CSS?

I am currently working on a Vue project and I am attempting to create a row of images with an icon positioned at the top left corner of each image. Here is my code snippet: <div v-for="(image, index) in images" :key="index" class=&q ...

Ensuring that the carousel images maintain a consistent size when switching between images

Issue with Carousel I have been struggling with a carousel feature on my website. Despite following the code provided on the Bootstrap website, I am facing an issue where the height and width of the entire div change when loading the next image. I have tr ...

Guidelines on incorporating a dynamically selected option into a dynamically populated dropdown menu

I have a challenge where I need to dynamically set the selected option text for a select menu based on the 'location' parameter passed into the 'updateDepartment' function. This parameter is obtained from a previous PHP request. The AJ ...