Identifying the Clicked Object in JavaScript

I have a simple movie search feature, but now I want to improve it so that when a user clicks on a movie, only that specific movie's title property is displayed. Currently, every movie that matches the search term is being shown.

How can I identify which movie has been clicked and pass only that movie's properties, instead of all movie objects? Do I need to implement a loop for this functionality?

I have included screenshots for reference - for example, if I click on the movie "John Wick", it should only display the title for movies matching "John Wick".

function search() {
    var userInput = $("#content-container-search").val().replace(/\s+/g,"%20");
    var searchTerm = "".concat(standardURL, apiKey, 'query=', userInput);
    var request = new XMLHttpRequest();
    clear(); //runs the clear function to clear existing DOM results to make way for the new ones
    
    request.open('GET', searchTerm , true);
    request.onload = function(data) {
        var data = JSON.parse(this.response);
        
        createList(data);
    }
    
request.send();
}

function createList(data){
    var app = document.getElementById("film-results");
    
    data.results.forEach(film => {
            console.log(film.title);
            var filmInfo = film;

            var Filmcontainer = document.createElement("div");
        Filmcontainer.setAttribute("class", "row film-container");
        
        var filmContainerLeftPanel = document.createElement("div");
        filmContainerLeftPanel.setAttribute("class", "film-container-left-panel column small-3");
        
        var filmContainerRightPanel = document.createElement("div");
        filmContainerRightPanel.setAttribute("class", "film-container-right-panel column small-9");
        
        var li = document.createElement("li");
        li.setAttribute("class", "film-container-right-panel-li");
        
        var ul = document.createElement("ul");
        
        var h1 = document.createElement("h1");
        h1.setAttribute("class", "film-container-right-panel-h1");
        h1.textContent = film.title;
        
        var ahref = document.createElement("a");
//            ahref.setAttribute("class", "button");
        ahref.setAttribute("data-open", "exampleModal1");
    
        var paragraph = document.createElement("p");
        paragraph.setAttribute("class", "film-container-right-panel-p");
        
        var paragraphMaxLength = 125;
        var filmOverview = film.overview;
        var trimmedFilmOverview = filmOverview.substr(0, paragraphMaxLength);
        trimmedFilmOverview = trimmedFilmOverview.substr(0, Math.min(trimmedFilmOverview.length, trimmedFilmOverview.lastIndexOf(" ")));
        trimmedFilmOverview = trimmedFilmOverview + "...";
       
    
        paragraph.textContent = trimmedFilmOverview;
        
        var baseImgURL = "https://image.tmdb.org/t/p/w154" + film.poster_path;
           
        var filmImage = document.createElement("img");
        filmImage.src = baseImgURL;
        filmImage.setAttribute("class", "film-container-right-panel-img");
        
//            film.forEach(filmImage.src.indexOf("null"))
//             filmImage.src = "/img/imagenotavailable.png";
    
        app.appendChild(Filmcontainer);
        Filmcontainer.appendChild(filmContainerLeftPanel);
        Filmcontainer.appendChild(filmContainerRightPanel);
        
        filmContainerLeftPanel.appendChild(filmImage);
        filmContainerRightPanel.appendChild(ul)
        .appendChild(li)
        .appendChild(ahref)
        .appendChild(h1);
        li.appendChild(paragraph);   


    generateModal(filmInfo);
        })
           
}


function generateModal(filmInfo){
    
        var modal = document.getElementById("exampleModal1");
        var h1 = document.createElement("h1");
        h1.textContent = filmInfo.title;
        modal.appendChild(h1);
        
        console.log(filmInfo);

}

https://i.sstatic.net/mmyzl.png https://i.sstatic.net/u1CQY.png https://i.sstatic.net/C39PJ.png

Answer №1

If you're interested, you might want to check out Event.target and currentTarget.

--UPDATE--

For example:

let buttons = document.querySelectorAll('.see-details');

buttons.forEach(button => {
  button.addEventListener('click', (film) => {
    let movieId = film.target.getAttribute('data-movie-id');
    
    console.log(movieId);
  });
});
<button data-movie-id="toy-story-1" class="see-details">See movie details</button>

Answer №2

To tackle this issue in JavaScript, utilize the event.target method.

var div = document.createElement('div');
document.body.appendChild(div);

var button = document.createElement("button");
button.innerHTML = "John Wick";
button.style.margin= "10px";
div.appendChild(button);

var button2 = document.createElement("button");
button2.innerHTML = "John Wick: chapter 2";
button2.style.margin= "10px";
div.appendChild(button2);

var button3 = document.createElement("button");
button3.innerHTML = "John Wick: chapter 3";
div.appendChild(button3);

function showName(e){
  alert("you have clicked "+e.target.innerHTML);
}

div.addEventListener('click', showName, false);

This code sets up 3 buttons that, upon clicking, will trigger the showName event. The event.target method allows us to identify which element initiated the specific event, such as a click.

Try running console.log(event.target) to retrieve detailed information on the event triggered.

Hopefully, this explanation is beneficial.

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

Navigating to the next page on a dynamic component in Angular 5 by

I'm uncertain if this scenario is feasible, but I have a page that fetches a list of items from an external API. There are currently 5 elements on the page, each acting as a link to its individual dynamically generated page through query strings. For ...

I encountered an issue when trying to launch my React application, as the CMD displayed an npm error message stating 'npm error! missing script:start'. Can someone offer assistance with this problem?

view image details Despite spending countless hours searching through past responses and attempting to resolve this issue, I have been unsuccessful. Upon entering 'npm create-react-app' in the terminal and navigating to the correct directory, I ...

Error: Material-UI prop type validation failed. Please specify either children, image, src, or component prop for CardMedia component. This error occurred at

I encountered an issue while trying to utilize the CardMedia component from Material-ui. The error message received was 'Failed prop type: Material-UI: Either children, image, src, or component prop must be specified. at CardMedia'. I attempted v ...

Is it possible to retrieve all data stored in AsyncStorage using React Native, while excluding the

In my current implementation, I am utilizing AsyncStorage.setItem() to store a string key and JSON object in AsyncStorage. For example: https://i.sstatic.net/qjiCD.png However, upon retrieving data from AsyncStorage using getAllKeys() and multiGet(), it h ...

Having issues with React-router v4's this.props.history.push() not functioning as expected

I'm attempting to programmatically redirect using the this.props.history.push(..) method, but for some reason it's not working. Here is the routing setup: import { BrowserRouter as Router, Route } from 'react-router-dom'; <Route ...

Is there a way to transfer the functionality of openssl_seal from PHP to NodeJS 18?

I'm looking to convert the openssl_seal() function from PHP to NodeJs. The code below is from my PHP SDK and works flawlessly, which is what I want to migrate: $ivLength = openssl_cipher_iv_length('AES-256-CBC') ?: 16; $iv = openssl_random ...

expanding the expressjs res feature

I am currently working on implementing an error and notification feature for my expressjs app. My approach was to add a function by calling: app.use(function (req, res, next) { res.notice = function (msg) { res.send([Notice] ' + msg); } }); ...

Creating dynamic and interactive web pages can be achieved by utilizing either $_POST or $_GET with Modal,

In the snippet below, you'll find the HTML code that pulls an array of 6 objects from a database and displays them in a Bootstrap row successfully. <div class="row products"> <?php while($product = mysqli_fetch_assoc($featured)) ...

A JavaScript code snippet to format a phone number in the pattern xx-xxxxxx

Please help me create a JavaScript function that can determine if the text in a textbox is a number. If it's not a number, I would like the function to focus on the textbox and change the format to look like this (xx-xxxxxx) when numbers are typed in, ...

jquery to create a fading effect for individual list items

I have a group of items listed, and I would like them to smoothly fade out while the next one fades in seamlessly. Below is the code I've been working on: document.ready(function(){ var list_slideshow = $("#site_slideshow_inner_text"); ...

Ways to verify an NPM package for non-JavaScript code

How can we determine if an npm package consists purely of JavaScript without any bindings or dependencies that require compiling? For instance, the node-speaker package (https://github.com/TooTallNate/node-speaker) requires compilation (mpg321), while req ...

Steps for creating a JavaScript session expiry notification:

Ensuring user session continuity is essential, especially before it expires. In a recent quest on Stack Overflow, I inquired about detecting a dead session and alerting the user. A solution involving AJAX/JSON was proposed, but it inadvertently kept the s ...

The npm install command failed due to a lack of suitable versions for pinkie-promise

I am currently attempting to perform a straightforward "npm install" from one of the repositories mentioned in a tutorial provided here Below is the content of the package.json: { "name": "react-playlist", "version": "1.0.0", "description": "A basi ...

Error: Attempting to use hooks outside the scope of a function component in react-native. Hooks can only be called within the body of a

Oops! An error occurred: Invalid hook call. Hooks can only be called inside the body of a function component. There are several reasons why this might have happened: You could have incompatible versions of React and the renderer (e.g., React DOM) Your cod ...

`Thoughts on Difficulty Attaching Child Elements in JavaScript with appendChild`

I am having trouble with appending some HTML that is being received as a string in a div. For some reason, the appendChild method is not working as expected. Here is my JavaScript code: var doc = document.getElementById("products"); var notes = doc.getEle ...

Using JavaScript regex to substitute white spaces and other characters

Here is a string I need to modify: "Gem. Buitentemperatuur (etmaal)" I want to remove all spaces, capital letters, and special characters from the string so that it becomes: "gem_buitentemperatuur_etmaal" ...

Unable to retrieve module from directive template in Angular

I am currently working on creating a wrapper component for ngAudio. This wrapper will act as the player with controls and will interact with ngAudio's functions. However, I am facing some scope issues with it. I can inject ngAudio into the component&a ...

Dynamic Content with Angular Bootstrap Tooltip

Currently, I am developing a cart application in Angular and utilizing Angular Bootstrap. The main requirement is to display a tooltip when hovering over the cart icon, with the content of the tooltip changing based on whether the item is already in the c ...

What is the best way to convert the value of "range" to floating point numbers in JavaScript?

Why is it that when I input a float number, like "3.4567890", as the value in an input field, it automatically gets converted to type 'int'? This conversion is not desired, as I want the value to remain as a 'number' or 'float&apos ...

Exploring ways to dynamically alter templates using the link function in Angular.js

Recently, I developed a directive called widget which functions similar to ng-view, but the template name is derived from an attribute. app.directive('widget', function() { return { restrict: 'EA', scope: true, ...