JavaScript - change image when clicked or hovered over

I have the knowledge to achieve this using jQuery, however, I am attempting to accomplish the following using traditional JavaScript. Can someone provide assistance:

document.querySelectorAll(".thumbnail").forEach(function(elem) {
    elem.addEventListener("click", function() {
        document.getElementById("mainImage").src = elem.src;
    });
});

My main objective is to be able to click on a thumbnail and see the main image change without relying on jQuery. While it may seem like a simple task, I am struggling to implement it in pure JavaScript. Thank you for any help provided.

Answer №1

With the power of jQuery, a multitude of features are automatically provided, making it challenging to replicate its functionality entirely. An example is demonstrated below, where all images with the class thumbnail have their onclick property set to trigger an image swap event handler.

onload = function () {
    var bigImg = document.getElementById("mainImage");
    for (var i = 0; i < document.images.length; i++) {
        var img = document.images[i];
        if (/\bthumbnail\b/.test(img.className) {
            img.onclick = thumbnailHandler;
        }
    }
    function thumbnailHandler(e) {
        bigImg.src = this.src;
    }
};

If IE7 support is not required, you can opt for a simpler implementation using document.querySelectorAll():

onload = function () {
    var bigImg = document.getElementById("mainImage");
    var thumbs = document.querySelectorAll(".thumbnail");
    for (var i = 0; i < thumbs.length; i++) {
        thumbs[i].onclick = thumbnailHandler;
    }
    function thumbnailHandler(e) {
        bigImg.src = this.src;
    }
};

Moreover, the rationale behind setting the main image's source as the thumbnail's source may be questioned. Is the full image being loaded into the thumbnail? This practice could lead to excessive downloads and escalate the page's memory consumption rapidly.

Answer №2

One simple and effective technique for handling events is event delegation:

const replaceMainImage = (e) => {
    if(~(' ' + e.target.className + ' ').indexOf(' thumbnail ')) {
        document.getElementById('mainImage').src = e.target.src;
    }
}

if(document.addEventListener) {
    document.addEventListener('click', replaceMainImage, false);
} else {
    document.attachEvent('onclick', function() {
        replaceMainImage({
            target: event.srcElement
        });
    });
}

Answer №3

It seems like you are looking to change the main image displayed on click of a thumbnail image. You have a thumbnail image '1thumb.png' associated with another image '1.png'. Here is a solution that worked:

In your <header>:

<script type='text/javascript'>
function myHandler(source){
    document.getElementById('mainimg').src=source;
}
</script>
...

Your thumbnail image code:

<img src='1thumb.png' onclick="myHandler('1.png')"/>

You can also use it for rollover triggering:

<img src='1thumb.png' onmouseover="myHandler('1.png')"/>

Give it a try: http://jsfiddle.net/d7Q27/7/

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

Are you in the business of building JavaScript hubs?

I have a unique setup where my express server is in charge of handling all routing and session functionalities. I've envisioned a system where logged-in users can connect to distinct "hubs" based on the location of each hub. My idea was to treat each ...

Retrieving CSS style values with Node.js

I am looking to design a new CSS style that includes the lowest and highest values. table[my-type="myStyle"] { width: 255.388px !important; } This code snippet is included in numerous CSS files within my style directory. ...

Is it Necessary to Wait for my Script Tag in React when Utilizing a CDN?

My current project involves the use of a CDN to load a script, which I am implementing through the useEffect hook directly in my component. Here is the simplified code snippet: React.useEffect(() => { const script = document.createElement('scri ...

What is the equivalent of this PHP array function in JavaScript/jQuery?

PHP is handling this scenario well. What would be the most efficient way to achieve a similar outcome in JS/jQuery? $statsArr['Status'][$s_id]['count'] = ($statsArr['Status'][$s_id]['count'] ?? 0) + 1; ...

What is preventing the item from utilizing the custom texture I created?

(Using IntelliJ to code everything) I am currently working on a Minecraft Mod and have encountered a strange issue. When testing my custom item, the name displays perfectly with spaces, but the texture fails to load. The error message I receive is as follo ...

Slider Footer Player for Rdio

I am currently working on replicating the interactive player footer design used by rdio (). When you click on the footer, a panel elegantly slides up to reveal additional content. Another example of this functionality can be seen on the website teehan lax; ...

AngularJS - directive template is not being compiled correctly

I am facing an issue with AngularJS. .directive('field', ['$routeParams', function($routeParams){ return { restrict: 'E', compile: function(tElement, tAttributes) { var template ...

Tips for crafting services using $q and $http requests while avoiding redundancy

Is there an elegant way to write AngularJS services without repetitive $q syntax? I currently write services like this: (function() { function ServiceFactory($q, $timeout, $http) { return { getFoo: function() { va ...

Having trouble getting Fullcalendar to show up on my cordova app

Currently, I am in the process of building a mobile application using ionic and cordova. My goal is to incorporate a timetable system utilizing Fullcalendar and a PHP page that showcases MySQL data in JSON format. Despite my efforts, I am encountering diff ...

Instructions on removing rows by using buttons within a JavaScript-generated table

This snippet displays JS code to create a quiz index table and HTML code to display the index. function load(){ var data = [ { "id": "qc1111", "quizName": "Quiz1", "course": "111", "dueDate": "1/ ...

What is the best way to generate a search link after a user has chosen their search criteria on a webpage?

In my search.html file, I have set up a form where users can input their search criteria and click the search button to find information within a database of 1000 records. The HTML part is complete, but I am unsure how to create the action link for the for ...

HTML text not lining up with SVG text

Why is the positioning of SVG Text slightly off when compared to CSS text with the same settings? The alignment seems awkwardly offset. Any help in understanding this would be much appreciated! Even with x: 50% and the relevant text-anchor property set to ...

pressing the downward arrow does not cause the number to decrease

I'm facing an issue with my code in this video. The increment is working when the upward arrow is clicked, but not the decrement. I suspect there's a problem with the jQuery code. Initially, I tried modifying from top to bottom, and changing +1 t ...

What steps can I take to ensure the reset button in JavaScript functions properly?

Look at this code snippet: let animalSound = document.getElementById("animalSound"); Reset button functionality: let resetButton = document.querySelector("#reset"); When the reset button is clicked, my console displays null: resetButton.addEvent ...

Tips for generating an input element using JavaScript without the need for it to have the ":valid" attribute for styling with CSS

My simple input in HTML/CSS works perfectly, but when I tried to automate the process by writing a JavaScript function to create multiple inputs, I encountered an issue. The input created with JavaScript is already considered valid (from a CSS ":valid" sta ...

Upload your existing image files to Dropzone

I have implemented image upload functionality using Dropzonejs in a form. To handle multiple form fields, I have set autoProcessQueue to false and processing it on click of the Submit button as shown below. Dropzone.options.portfolioForm = { url: "/ ...

What is the best way to exclude a particular character from a text element utilizing jquery?

Looking to extract the numerical value from a div containing: <div class="balance"...>$500.48</div> The goal is to retrieve 500.48 as a number, not a string. One approach is to use alert($(".balance").text()) to verify that the content is ret ...

Exploring resource file entries in JavaScript for an MVC application

In my MVC application, I am faced with the challenge of reading values from a resource file and passing them to a JavaScript file. Currently, I am calling a separate JavaScript function from a cshtml file, which in turn passes parameters containing the res ...

Configuring a JavaScript calendar with custom margins

Having trouble selecting a date with the Bootstrap datepicker class. After running the snippet, the calendar appears below the textbox: <input type="text" class="form-control datepicker" name="due_date" id="due_date" onclick="calendar_up()" value="" pl ...

Having trouble retrieving the value of a custom directive attribute

My custom directive, named "mycomponent", has the following configuration: restrict: 'AE', templateUrl: 'template.html', scope:{ sTransactionType: '=transactionType', sStorageVariable: '=storageVariable&apos ...