Resizing Images with JavaScript

I have been attempting to create a functionality where an image enlarges itself upon a user click and reverts back to its original size when the cursor is moved away. However, I am facing difficulties as the image is not responding, it's a large 800 pixel image.

behaviour.js:

document.addEventListener("DOMContentLoaded", function(event) {
    alert('Hello!');
});

document.getElementById("smart_thumbnail");

var thumbnailElement = document.getElementById("smart_thumbnail");

thumbnailElement.addEventListener("click", function() {
    alert('I saw you click');
});

var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.className ="small";

if (thumbnailElement.className == "") {
    // write here the code that will execute if the image is big
}

index.html:

 <p>An 800 pixel image</p>
        <img id="smart_thumbnail"  src="http://calmground.com/wp-content/galler\
y/our-calm-ground/calm.jpg" class="small"  >

@kinglish, I understand that img.small is a CSS code, though I haven't copied your specific code, but I have followed the instructions. It seems that something is not working correctly in my file as the functionality is not running as expected.

Index.html:

<p>An 800 pixel image</p>
                <img id='smart_thumbnail'  src='http://download.baps.org/wallpapers/14.bmp' class='small'  >

behavior.js: I made some modifications

*document.addEventListener("DOMContentLoaded", function(event) {
   //  alert('Hello!');
});

document.getElementById("smart_thumbnail");

var thumbnailElement = document.getElementById("smart_thumbnail");

thumbnailElement.addEventListener("click", function({
    var theElement = event.target;
    // to toggle class names
    if (theElement.classList.contains('small')) {

        theElement.classList.remove('small');
        theElement.classList.add('large');
    }else {
        theElement.classList.remove('large');
        theElement.classList.add('small');
    }

});

styles.css:

img.small {
    width: 50px;
}

img.large {
    width: 200px;
}

Answer №1

Learn how to change the image size onclick and resize it when not hovered:

var hoverEnabled = false;
document.addEventListener("DOMContentLoaded", function(event) {
    alert('Hello!');
});

document.getElementById("picture_thumbnail");

var thumbnailElement = document.getElementById("picture_thumbnail");

thumbnailElement.addEventListener("click", function() {
    this.classList.toggle('small');
    document.getElementById("label").innerHTML = "An 800 pixel image";
    hoverEnabled = true;
});

thumbnailElement.addEventListener("mouseleave", function() {
  if (hoverEnabled) {
    this.classList.toggle('small');
    document.getElementById("label").innerHTML = "A 100 pixel image";
    hoverEnabled = false;
  }
})
.small {
  height: 100px;
}
<p id="label">A 100 pixel image</p>
<img id="picture_thumbnail"  src="https://placekitten.com/400/800" class="small">

<style>
  .small {
    height: 100px;
  }
</style>

<p id="label">A 100 pixel image</p>
<img id="picture_thumbnail" src="https://placekitten.com/400/800" class="small">

<script>
  var hoverEnabled = false;
  document.addEventListener("DOMContentLoaded", function(event) {
    alert('Hello!');
  });

  document.getElementById("picture_thumbnail");

  var thumbnailElement = document.getElementById("picture_thumbnail");

  thumbnailElement.addEventListener("click", function() {
    this.classList.toggle('small');
    document.getElementById("label").innerHTML = "An 800 pixel image";
    hoverEnabled = true;
  });

  thumbnailElement.addEventListener("mouseleave", function() {
    if (hoverEnabled) {
      this.classList.toggle('small');
      document.getElementById("label").innerHTML = "A 100 pixel image";
      hoverEnabled = false;
    }
  })
</script>

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

CORS request results in unsuccessful cookie setting in browsers except for Firefox where Set-Cookie header is detected; notably, Chrome does not show the header

I'm experiencing an issue with setting cookies from a NodeJS server to the client using JQuery and AJAX. Despite seeing the Set-Cookie headers in the response, the cookies are not showing up in the document.cookie string. I would greatly appreciate it ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

What is the process for updating a placeholder text after the user makes a guess or enters

My latest project involves creating a fun guessing game where players have to identify the driver based on the teams they have driven for. The game displays the number of guesses allowed and keeps track of how many attempts the player has made so far. For ...

Is there a way to position a ListItem (using React) in the lower left corner in this specific case?

import * as React from 'react'; import { styled, useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar from '@mui/material/Ap ...

Closing Note in Drupal

Is there a way to adjust the footer message in Drupal without logging into the dashboard? I've checked all the files in cPanel, but I can't seem to locate the actual HTML for the website. I am only able to customize the body content, not the fo ...

What is the process of handling the event queue in Node.js?

Exploring the intricacies of the Node.js architecture has left me with several questions: 1) Is the event loop a component of libuv or v8? 2) How does the callback in the event queue transition to the call stack for execution after being delegated by the ...

Utilize res.render in Node.js to pass multiple data arrays to the view

I am facing an issue with populating two separate selects in my view with different arrays. Can anyone guide me on how to pass two distinct JSON objects using res.render? I have attempted the method below without success. const result1 = {data1: "val ...

Customizing the MUI X Sparkline: Incorporating the percentage symbol at the end of the tooltip data within the MUI Sparklinechart

Presented below is a SparklineChart component imported from MUI X: import * as React from 'react'; import Stack from '@mui/material/Stack'; import Box from '@mui/material/Box'; import { SparkLineChart } from '@mui/x-chart ...

Displaying text on hover and showing a text box when a link is clicked using CSS and JavaScript

Hovering over the text will display "Edit," and clicking on it will reveal a text box. This function will be used to update content using ajax. HTML: <table> <thead> <tr> <th> Name </th> <th> Age </th> ...

Creating code to ensure a div element is displayed only after a specific duration has elapsed

Can anyone help me with coding to make a div appear on a website after a specific amount of time? Here's an example of what I'm trying to achieve: <div class="container"> <div class="secretpopout"> This is the hidden div that should ...

Organize items within a compartment using Bootstrap3

I have decided to update my website to Bootstrap3 and encountered a common issue that many others seem to be facing as well. I am trying to evenly distribute 4 elements, each approximately 220px wide, inside a 990px container. In the old version of Bootstr ...

Programmatically installing Npm is ineffective

I am currently attempting to interact with the npm api programmatically, as illustrated in the code snippet below: var npm = require("npm"); npm.load(npm.config, function (err) { npm.commands.install(["express"], function(err, done) { console ...

FF and IE9 cause issues with Backbone application

I recently finished developing a web application using Backbone, ICanHaz, and jQuery. If you want to check it out, click on this link: While the app works flawlessly in Chrome (version 12.0.742.122), it encounters issues in Firefox 5 (5.0.1) and Internet ...

What is the method to assign a value to ng-class in Angularjs?

I need to categorize items in a list by assigning them classes such as items-count-1, items-count-2, items-count-3, items-count-4, based on the total number of items present. This is how I would like it to appear: li(ng-repeat="area in areas", ng-class=" ...

Switching between two identical components can be easily achieved with VueJS

Assume I have a file named foo.vue, which I import into the parent component as components called a and b, and they are displayed based on a variable called show. When switching between components a and b in the parent without setting show = null, various ...

Express, the mongoose package delivers a response of an empty array

I have encountered a common issue regarding pluralization with mongoose default model names. Despite trying various solutions, the problem persists as I am getting an empty array as the result. In my local mongoDB database, there are 2 documents in the "us ...

Adjusting the date format within an AJAX success callback: alter how the date is displayed

Attempting the following code: var second_date = moment(currentdate).format('DD-MM-YYYY'); The result is: Uncaught Reference Error: moment is not defined. success: function(response){ var len = 0; if(response != n ...

To begin, select and upload two files for processing. Once complete, you can download the newly generated

I'm encountering difficulties attempting to upload two files to a php script and have the page download a newly merged file without redirecting to a different page. I do not wish to store any files on the server due to their potential size (2MB) as b ...

My extension seems to be missing the content script I uploaded

I am currently developing an extension for Google Chrome. My goal is to create a content script that can retrieve meta tags from the tab when the popup is clicked. In my manifest, I have included the following permissions: "content_scripts": [{ "js" ...

What is the best way to showcase this information within my columns?

I'm facing an issue with VueJS. I have a large dataset that I want to display in columns in a specific order. How can I properly insert the code for this? Thank you for any assistance. [ { "sort": 0, "title": "My title", "description": ...