Unable to change image in JavaScript accurately

Currently in the process of building a website and encountered a small problem. I have three pictures, two small ones and one large one. What I want is for clicking on a small picture to replace the larger one. I have a JavaScript function that accomplishes this, but there is a slight issue. There are 3 sets of these three pictures, so when a small image is clicked to swap with the larger one, it replaces all three large images instead of just the one in its section. Any advice or suggestions would be greatly appreciated. Thank you!

The JavaScript Function

$(document).ready(function(){
    $('img').click(function(){
        var url = $(this).attr('src');
        var bigUrl = $(this).parents('.picture-container').find('.large-picture > img').attr('src');
        $('.large-picture > img').attr('src', url);
        $(this).attr('src', bigUrl);
    });
}); 

An Example Section

<div class='main-content'>
    <div class='picture-container'>
        <div class='large-picture' style='width:50%;height:100%;float:left;'>
            <img src='close_table_dupontstudios.png' width='100%' height='100%'>
        </div>
        <div class='picture-content' style='float:right;width:45%;height:100%;'>
           ...
        </div>
    </div>
</div>

Answer №1

Instead of using a generic class selector like .large-picture to change the image src, consider using a more specific selector to target only the desired element. It seems that all three sections have elements with this class, causing them all to be affected by your current selector.

To target the appropriate element, you could utilize an id or combine parents() and find() as shown in your previous code snippet:

$(this).parents('.picture-container').find('.large-picture > img').attr('src', url);

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

Having trouble with array slicing functionality?

I received a json list and stored it in an array. {"event_date": "2016-12-07 01:39:41","created_at": "15/11/2016 às 06:10"} Within this list, there is an attribute called "_date": "2016-12-07 01:39:41". I am attempting to extract the year '2016&apo ...

Handling the width and borders of CSS cells that are positioned outside of a table

Welcome! I recently created a simple gantt organizer as part of a demo. My goal was to make the main table scrollable while keeping certain columns "frozen" for easy visibility when navigating through the data. To achieve this, I followed some advice found ...

PHP AJAX integration for select2 multi-select feature

I am attempting to populate my select2 multiple selection using ajax, but I am not getting any results back. Here is my HTML code snippet: <input type="hidden" id="instituicaoSel" tabindex="-1" class="select2-offscreen" value=""> Javascript code: ...

The ng2-dnd library encountered an issue: StaticInjectorError in AppModule with SortableComponent pointing to ElementRef

I have been experimenting with the ng2-dnd sortable container from ng2-dnd. Below is the HTML code for my component: <div class="row"> <div class="col-sm-3"> <div class="panel panel-success"> <div ...

HTML5's video tags are capable of displaying video content without audio playback functionality

My current project involves importing videos using PHP, utilizing a video tag. However, I've encountered an audio issue while doing so. I've tried various codes such as: <video controls> <source src="https://www.w3schools.com/html/mov_ ...

Is it possible to adjust the speed of an animation within a-frame?

<a-camera id="view"> <a-animation attribute="position" from="30 30 30" to="-1 1.5 -2" delay="100"></a-animation> <a-cursor color="black"/> </a-camera> I encountered an issue while working on a we ...

Is it feasible to integrate "tutorials" in HTML and CSS?

I have a vision to incorporate a "guider" into my application, a dialog box designed to help guide users by visually introducing them to significant features: Specifically, I am interested in functionalities like attaching the guider to an element on the ...

jQuery AJAX issues on Safari and iOS gadgets

I'm facing a compatibility issue specifically with Safari and all iOS devices. I've developed this jQuery code for a project, but it seems to have trouble working with Safari. Interestingly, it works perfectly fine with Chrome, Firefox, and even ...

Developing a feature for automatic connection on LinkedIn's advanced search platform

Is there a way to automate connecting with people you find using the LinkedIn advanced search feature? While there are guides on how to do this from the 'people you may know' page, I've only come across the code below that is supposed to wor ...

Unable to display a horizontal scroll bar

I'm having some trouble with implementing a horizontal scroll feature and can't seem to make it work. If you want to take a look, here is the fiddle Please provide me with assistance in identifying what mistakes I may be making edit Here is th ...

Is there a way to bind the sortablejs results to the vue data?

How can I pass the result to data in Vue? I am confused with how to implement sortable features using Vue and SortableJS. The project utilizes Bootstrap-Vue.   <div>     <b-table v-sortable="sortableOptions" striped hover :items="items"> ...

Pythonanywhere is throwing a NOREVERSEMATCH error when accessing /blog, whereas the localhost is functioning flawlessly

PythonAnywhere is encountering an issue with NOREVERSEMATCH at the /blog location, but it functions perfectly fine on localhost. I have taken the steps to resave the project, committed it to GitHub again, and pulled it on PythonAnywhere. Despite these eff ...

"Securing Your Web Application with Customized HTTP Headers

I'm currently working on setting up a POST request to a REST API (Cloudsight) with basic authorization. Here is the code I have so far: var xhr = new XMLHttpRequest(); xhr.open("POST", "http://api.cloudsightapi.com/image_requests", true); xhr.setRequ ...

Is there a way to trigger an action every 5 minutes in ReactJS?

I am attempting to trigger an action every 5 minutes after a user logs in. The action should only be dispatched once the user is logged in and then continue at 5-minute intervals. I initially tried using the setInterval method, but encountered an issue whe ...

Modify the HTML input type color in React.js only after releasing the mouse button

<input className="color-palatte" type="color" onChange={(e) => onColorChange(e)} /> When interacting with the color palette, I have set up an API call to trigger only when I release the slider instead of continuous calls while sliding over the co ...

Error encountered: The jQuery DevExtreme datagrid function $(...).dxDataGrid is throwing an Uncaught TypeError

I'm encountering an issue with the DevExtreme DataGrid while using ASP.NET MVC. Even after downloading NuGet packages, adding scripts to the head section, I am still facing this error: Uncaught TypeError: $(...).dxDataGrid is not a function. Do I ...

Just starting out with Boostrap; looking for ways to tidy up this code and achieve the intended effect

UPDATE: Check out the revised JS Fiddle link at the end of this post; I managed to achieve the desired result, but I believe there's room for improvement in the code! After experimenting with HTML/CSS for some time, I'm now working on my first l ...

How to extract just the year from Material-UI's date picker in React

const displayYearOnly = (date) => { const year = date.getFullYear(); console.log(year); }; return ( <div style={{ marginRight: "20px" }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DemoContainer componen ...

Tips for showing a single progress message when uploading multiple files on eleme.io [vuejs]

Tech Stack: Utilizing Vuejs with element.eleme.io framework. Objective: To implement a feature that allows users to upload multiple files while displaying only one "in progress message". To handle image uploads, we are integrating . During the upload pr ...

Switching from a single-file revealing module pattern implementation in JavaScript to a multi-file setup with import functionality

As someone diving into the realm of JavaScript design patterns with limited experience using require or import, I find myself in a situation where I have a single module containing various functions and private variables all within one file. It has become ...