Inserting an image into a <div> means adding a reduced-size image numerous times to fill the Div

I have encountered an issue while using the code provided in the CodePen link below to paste an image into a Div. The problem is that when I paste a small image, it shows up multiple times within the Div if clicked on after pasting. My goal is to display the image only once and prevent the Div from being filled with redundant copies of the same image.

Check out the code here

 $('.active').removeClass('active');
 $this.addClass('active');

 $this.toggleClass('contain');

 $width.val($this.data('width'));
 $height.val($this.data('height'));
 if ($this.hasClass('contain')) {
 $this.css({'width':$this.data('width'), 'height':$this.data('height'), 'z-   index':'10'})
 } else {
 $this.css({'width':'', 'height':'', 'z-index':''})
 }

})
})

View example of multiple images in div

Answer №1

The reason behind this behavior is the toggling of the CSS class .contain, which also toggles its background-size property. This specific class sets the background size to cover.

.contain {
    background-size: cover;
}

Upon clicking, the class is removed, causing the background-size to revert to the original image size display. In addition, since the default value for background-repeat is set to repeat, the image repeats in both directions to cover the element.

To prevent the repetition, a simple solution is to include:

.target {
    background-repeat: no-repeat;
}

It's important to note that this adjustment will not resize the element to fit just one image.

Answer №2

Consider using the background-repeat property for this issue.

background-repeat: no-repeat;

$('.active').removeClass('active');
 $this.addClass('active');

 $this.toggleClass('contain');

 $width.val($this.data('width'));
 $height.val($this.data('height'));
 if ($this.hasClass('contain')) {
 $this.css({'width':$this.data('width'), 'height':$this.data('height'), 'z-index':'10', 'background-repeat':'no-repeat'})
 } else {
 $this.css({'width':'', 'height':'', 'z-index':'','background-repeat':'no-repeat'})
 }

})
})

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

Using a tpl file with added jquery, even with literal tags, does not function properly

I have been struggling with implementing a jQuery script in my tpl file. Despite using the literal tags, the script is not functioning properly. Can anyone help me figure out what's going wrong? <script type='text/javascript'> {litera ...

What is the best way to create a compound query in Firebase?

I am working on a TypeScript script to search for a city based on its population... import { getFirebase } from "react-redux-firebase"; ... get fb() { return getFirebase(); } get fs() { return this.fb.firestore(); } getCollection(coll ...

Tips for smoothly adding new content to a jQuery AJAX autoupdating div

I'm currently working on a div that pulls data from an external PHP file, which loops through results from a MySQL query. My goal is to have this div update every 5 seconds using AJAX, with only the new results smoothly fading in at the top of the lis ...

Using the express.Router instance for handling errors can be a useful tool in your development

Based on the documentation, it states that any nodejs express middleware function has the capability of being swapped out by App or Router instances: Given that router and app adhere to the middleware interface, they can be used just like any other midd ...

Parsing images on Android and iPhone devices

I had an idea for creating a unique Android and/or iPhone app that involves taking a picture of text and having the app parse it. For instance, snapping a photo of a sentence or fragment would allow the app to provide more information about a book such as ...

Image not showing up in MUI React

When trying to showcase my images using the itemDate.js file: const itemData = [ { img: "../assets/photos/photoportrait.jpeg", title: 'Breakfast', }, and calling it within my Portfolio component: import * as React f ...

What causes the cleanup function in React hooks to be triggered upon reopening a previously closed tab?

There seems to be an issue with closing a tab and then undoing that action. This causes all the cleanup functions in the component to execute, resulting in the abortion of new fetches needed to load the component. This behavior is observed only on Safari ...

Receiving a data response from AJAX in Node.js is easy with these steps

Right now, I am in the process of learning express, ajax, and nodejs. My current focus is on making ajax and nodejs communicate with each other. I have been sending a client request using ajax to a nodejs server. Everything seems to be working fine up unti ...

Leverage environment variables within your index.html file

Currently, I am using Angular and I am encountering an issue while attempting to utilize an environment variable in my index.html for Google Analytics. I have attempted the following approach: <script> import {environment} from "./environments/e ...

Could my HTML security measures be vulnerable to exploitation?

I have successfully developed a function that accomplishes the following: It accepts a string as input, which can be either an entire HTML document or an HTML "snippet" (even if it's broken). It creates a DOMDocument from the input and iterates throu ...

Steps for adding a React Class Component into a Modal that is not within the React Tree

Our project is built using PHP MVC Framework and we initially used jQuery as our main JavaScript framework for handling UI activities. However, we have now transitioned to using React.js. My query is about how to inject or append a React Functional/Class-b ...

Click to switch CodeMirror's theme

http://jsbin.com/EzaKuXE/1/edit I've been attempting to switch the theme from default to cobalt and vice versa, toggling each time the button is clicked. However, I am facing an issue where it only switches to the new theme once and doesn't togg ...

Extracting CSS data and storing it in a SQL database

Hello there, I've created a div using CSS like this: echo '#'. $pess2['naam'] .' { width: 190px; height: 90px; padding: 0.5em; float: left; left:'. $pess2['left'] .'px; top:'. $pess2['top'] ...

Toggle visibility of an Angular 4 component based on the current route

Hello there, I'm facing an issue and not sure if it's possible to resolve. Essentially, I am looking to display a component only when the route matches a certain condition, and hide another component when the route matches a different condition. ...

What is the process for transforming a promise outcome into JSON format?

My current challenge involves using axios to retrieve JSON data from an external API in my backend and then passing it to the frontend. The issue arises when I attempt to log the result in the frontend, as all I see is a promise object instead of the actua ...

Full-screen and auto-cropping capabilities are featured in the Bootstrap 4 carousel design

Is there a way to make full-width images in the bootstrap 4 carousel cropped based on position: center, background: cover to prevent scrolling issues? I attempted to follow advice from this webpage but encountered stretching and scroll-bar problems with d ...

The new FormData(form) method unexpectedly returns an empty object

In this scenario, I am aiming to retrieve key-value pairs. The form on my page looks like this: <form id="myForm" name="myForm"> <label for="username">Enter name:</label> <input type="text" id="username" name="username"> ...

The error message "props.text is undefined in React Native" indicates that there is an issue with accessing the property text within

//**// import { StatusBar } from 'expo-status-bar'; import {StyleSheet, Text, View, Button, TextInput, ScrollView, FlatList} from 'react-native'; import {useState} from "react"; import GoalItem from "./components/GoalItem"; export defau ...

A comprehensive guide on leveraging redux's useSelector to access state data and execute a database fetch operation

Working on a project with redux, I am facing the challenge of creating a useSelector function that can determine if the values in the redux state are default. If not, it should trigger a database request to update the state. This task seems complex and I&a ...

Vue.js - The dissonance between data model and displayed output

Below is a simplified example of my issue: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script> <script src="https://unpkg.com/vue/dist/vue.js"></script> ...