Changing a background image url using jQuery by clicking a button

I'm struggling to find a way to use jQuery to add a background image URL to my CSS. Everything I've attempted so far has been unsuccessful.

let button = document.querySelector('form button.btn')
button.addEventListener('click', () => {
  $(".img").css("background", "url('/images/Codax.jpg')");
})
div.img {
  height: 450px;
  width: 350px;
  background-color: #fff;
  -webkit-box-shadow: 7px 1px 15px 0px rgba(0, 0, 0, 0.55);
  -moz-box-shadow: 7px 1px 15px 0px rgba(0, 0, 0, 0.55);
  box-shadow: 7px 1px 15px 0px rgba(0, 0, 0, 0.55);
  background: url('');
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  border-radius: 5px;
}
<div class="perfil-img">
  <div class="img">
  </div>
</div>
<form>
  <button type="button" class="btn">Salvar</button>
</form>

EDIT

Follow: In the link is the directories used in the project. Folders

This Html is called from a FetchContent. The desire is to add the image in html that FetchContent calls.

<li class="nav-item">
  <a class="nav-link" href="#" a-view="infoPessoal" onclick="fetchContent(this)" a-folder="administrativo">
    <i class="fas fa-user-tag"></i>
    <!-- Icones -->
    Pesssoal
  </a>
</li>

Answer №1

To display the image, use the file path ../images/Codax.jpg. Remember, the path should be relative to the location of the css file. You can go up one directory by using ../.

 $(".img").css("background", "url('../images/Codax.jpg')")

Answer №2

In order to maintain separation of concerns, my suggestion would be to create a CSS class that includes the corresponding background image setting, then use the .toggleClass() method to toggle the class.

.custom-background{
background : url('http://lorempixel.com/400/200');
width : 100%
/*Any other desired parameters*/
}

Here's how you can achieve this in JavaScript:

$( "button" ).click(function() {
  $(".img").toggleClass( "custom-background" );
});

By following these steps, you should be able to successfully apply the background image when needed.

Answer №3

It is recommended to utilize the CSS property background-image in place of simply using background for better optimization.

 $(".img").css("background-image", "url('/images/Codax.jpg')");

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

Vue js is throwing an error because it is unable to find the "buscador" property or method that is being referenced in the render function

I am currently diving into the world of laravel combined with Vue js. I am working on integrating a search engine using vue js components, and I would greatly appreciate any help you can provide. Thank you in advance. Below is the Vue js component where t ...

Transmit data using both jQuery and JSON technology

I'm struggling to figure out how to send a JSON structure with a file using AJAX. Whenever I try to include an image in the structure, I encounter an error. var professionalCardNumber = $("#professional_card_number_input").val(); var professi ...

Take away the dropdown selection once the form has been submitted

Every day, a user fills out a form ten times. They choose an option from the dropdown menu, fill out the form, and submit it. I am looking for a solution to either remove the selected option once it's been submitted or mark it as complete by highlight ...

Preventing click event from bubbling up the DOM: Using Vue's @click

How can I access the child elements within a parent component? <div v-on:click.stop.prevent="onClickTemplateHandler"> <div> <h3 style="">Title</h3> <p>{{ lorem }}</p> </div> ...

Is there a way to perfectly center this image with the rest of my text content?

Seeking assistance in aligning this image to the right alongside other text content. Currently, when the code is executed, the image is pushed down and positioned below the text on the right side. Ideally, I would like the image to be aligned evenly with ...

CSS animation: Final position once the vertical text has finished scrolling

I have designed a CSS-animated headline with a leading word and three vertically-scrolling/fading statements to complete the sentence, inspired by the style used on careers.google.com. The animation runs through three cycles and stops, leaving the third st ...

Prevent users from downloading images

I'm trying to prevent image downloads by regular users, like so: <div style="background-image: url(img.jpg); background-size: cover; background-repeat: none; "> <img src="wtrmrk.jpg" style=" opacity: 0; " /> </div> If the img.jpg s ...

finding the initial element within an object using lodash in javascript

Recently, I came across some data in the form of an array of objects. For instance, let me share a sample dataset with you: "data": [ { "name": "name", "mockupImages": "http://test.com/image1.png,http://test.com/image2.png" }] ========================== ...

The bottom section of the webpage fails to follow the CSS height or min-height properties

Taking into account the question I raised earlier: How can a div be made to occupy the remaining vertical space using CSS? I received an answer which I have been experimenting with lately: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "htt ...

The css values for component _nghost-c0 in an Angular application

Recently, I've been delving into Angular 5 and couldn't help but notice the peculiar html tags with ng generated attributes like _nghost-c0 and _nghost-c1... This got me wondering, what exactly do these attributes signify? [_nghost-c3] .employee ...

Is there a way to display a loader when an item is selected from a dropdown menu? For example, while data is being fetched from the backend, can we

This is the HTML form division I have created: <div class="col-lg-2 "> <select name="limitCount" id="limitCount" ng-model="limitCount" class="form-control col-md-2 panel-refresh" ...

What is the best way to set the default display of the first option value in a dynamically populated <select> dropdown menu?

I have a field that displays options dynamically. I am looking to set the first option value as the default in the select field. Can someone provide assistance with this? <div class="col-lg-4"> <select name="trader" class="form-control" id="sele ...

I've been attempting to develop a React application, but I consistently encounter the following error: "npm ERR! cb() function was never invoked!"

Here is the issue at hand: HP@DESKTOP-1HP83V8 MINGW64 ~/Desktop/Web-Development (master) $ npx create-react-app my-app A new React app is being created in C:\Users\HP\Desktop\Web-Development\my-app. Packages are being installed. ...

I need to access a webpage using VBA without relying on Internet Explorer for logging in

I need to access the website by logging in. However, I am facing difficulty in using it. Unfortunately, I am unable to share the username and password due to confidentiality reasons. Below is the code snippet that I have: Sub checkdownload() Dim u ...

Encountered an error while web crawling in JavaScript: Error - Connection timeout

I encountered an error while following a tutorial on web crawling using JavaScript. When I execute the script, I receive the following errors: Visiting page https://arstechnica.com/ testcrawl ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

Having trouble receiving any ringing status in nextjs while utilizing the getstream SDK

I attempted to integrate the getstream video SDK for calling from the caller to the callee. While I can successfully create calls from the caller side, I am not receiving any status updates about the call on the callee side. Below are my codes for the cal ...

Tips for transforming a JSON response into an array with JavaScript

I received a JSON response from an API: [ { "obj_Id": 66, "obj_Nombre": "mnu_mantenimiento_de_unidades", "obj_Descripcion": "Menu de acceso a Mantenimiento de Unidades" }, { "obj_Id": 67, "ob ...

What is the process for removing the body of a table?

My goal is to reset the table body, which has been filled with JavaScript loaded data previously. https://i.stack.imgur.com/7774K.png ` getTableData = function (clicked_id) { if (clicked_id != '') { $.ajax({ async : f ...

Tips for transferring client-side data to the server-side in Angular, Node.js, and Express

Seeking a straightforward solution to a seemingly basic question. I am utilizing Angular's $http method with a GET request for a promise from a specific URL (URL_OF_INTEREST). My server runs an express script server.js capable of handling GET reques ...