Utilizing a dynamic URL to set the background image of a div element (with the help of

Currently, I am in the process of designing a user registration page that allows users to input an image URL and view a preview of the image within a designated div. The div already contains a default image set by a specific class. The HTML code for displaying the user's image is as follows:

<div id="user-image-preview" class="col-md-4 col-sm-12 user-image-preview">  </div>
<button id="preview-image">Preview image</button>

The CSS styling for 'id=user-image-preview' and the 'user-image-preview' class is outlined below:

#user-image-preview {
height: 300px;
width: 300px;
border-radius: 50%;
position: absolute;
left: 200px;
top: 150px;
background-size: cover;
}

.user-image-preview {
background-image: url("https://cdn1.iconfinder.com/data/icons/unique-round-blue/93/user-512.png");
background-size: cover;
}

This snippet showcases the input section of the form where users can provide the image URL:

<div class="form-group">
    <i class="fa fa-picture-o" aria-hidden="true"></i>
    <label for="img">Image</label>
        <input id="user-image-set" type = "text" class ="form-control" placeholder = "Enter image URL" name = "image">
 </div>
 <button id="submit-login" type ="submit" class="btn btn-primary btn-lg  disabled">Signup</button>

In order to replace the default image with the contents of the input field, I utilized the following jQuery script:

$("#preview-image").on("click", function() {
var newUserImage = $('#user-image-set').val();
    $("#user-image-preview").removeClass("user-image-preview");
    $("#user-image-preview").css("background-image", "url('newUserImage')");
    console.log(newUserImage)
})

(I included the console.log statement to validate the accuracy of the variable retrieval).

My assumption is that there might be an issue with how quotes are being used within the URL segment of the function, but I have yet to pinpoint the correct method of referencing this variable.

Answer №1

Since newUserImage is a variable, there's no need to enclose it in quotes '' therefore, modify the following line

$("#user-image-preview").css("background-image", "url('newUserImage')");

to

$("#user-image-preview").css("background-image", "url(" + newUserImage + ")");

Answer №2

I found the perfect fix:

$("#profile-picture").css("background-image", "url(' " + newProfilePic + "')");

Don't forget to include ''

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

Extract the URL's name using jQuery

Looking for a way to extract the "step2" value from a given URL? Here's a JavaScript solution: const url = window.location.href; console.log(url); For example, let's consider this URL: http://www.myproject.com/wp/?edit_project=797#step2=projec ...

Choose the text by clicking on a button

I currently have: <span class="description">Description 1</span> <button class="select">Select!</button> <span class="description">Description 2</span> <button class="select">Select!</button> <span clas ...

Issue with JQuery causing maxlength input not to work

Is there a way to use JQuery to set the maxlength attribute for an input[type='text'] while users are typing, so that once the max value is reached, input will stop? This is the code I have been trying: $(document).ready(function(){ $(&apos ...

Is there a restriction on the number of stylesheets per page in Internet Explorer 8?

Discussing the limitations of CSS in a forum thread, a user shared insights: A user mentioned that Internet Explorer has is known to have a restriction of 4096 CSS rules per file. For more information, check out this source. Additionally, there might be ...

Adjusting height in CSS can be done dynamically based on the content within

Currently, I am working on a project where I need the submenu to adjust based on content. The issue is that right now, the submenu has a fixed capacity of 4 items. For example, when you click on 'sale', it displays 4 submenu items perfectly. Howe ...

Running PHP code within an HTML file served by PHP

A unique and innovative approach was taken by incorporating a DIV element in the HTML code, which dynamically populates with content from the main_login.php file. The main_login.php file plays a crucial role in loading the homepage with member-specific con ...

Two neighboring sections containing dynamic elements. One section automatically adjusts its size to fit the content, while the other allows

I need to display 2 adjacent boxes with dynamic content rendered using Angular. The Container should have the same height as Box1. The height of Box2 may vary due to its dynamic nature, but it should never be taller than Box1. If it does become higher, a s ...

Obtain the value of a dynamically selected option

I am facing an issue with my select options where I want the input field to be automatically filled with the 'data-place' value of the selected option whenever it changes. This includes a few dynamic select options. $(function() { // Hand ...

Every time I refresh the page, new data is inserted into the MySQL database

After clicking the button, I expect data to be inserted into my MySQL database. However, it only inserts the data when I manually reload the page. Below is the code snippet: <script> function minuscredits() { alert("hah"); <?php mysql ...

Unusual behavior exhibited by JavaScript's eval() function

As part of my website design, I am developing custom Message Boxes that can display normal OK dialogs as well as Yes/No dialogs. These popups prompt the user to click either "OK" or "Yes/No", which then triggers corresponding callbacks executed using eval( ...

What is the best way to bring an image into your nextjs project?

I have a question about importing images into my Next.js project. I created an array of objects and want to import an image stored in a folder on my laptop, specifically in the src folder rather than the public folder. How can I properly achieve this in ...

Can one intercept the window.location.replace event?

Suppose I am currently browsing the URL "example.com/somepage#somehash" and then decide to execute window.location.hash = "anotherhash", the URL will be updated to "example.com/somepage#anotherhash". This action triggers the window.hashashchange event. On ...

How can we ensure successful validation using Jquery?

I'm currently working on a basic form that includes text fields. Whenever these text fields are modified, an Ajax function is called to save the changes. However, I am facing a challenge in validating these fields using jQuery before the change even ...

Replace the facebook plugin using JQuery libraries

Does anyone know how to remove the like button on top of the 'Like box' Facebook plugin using JQuery? I have imported the like box from Facebook and I want to eliminate this like button, but Facebook does not allow me to do so. Therefore, I am t ...

Using just a simple HTML code, the d-flex feature in Bootstrap seems to be malfunctioning

Embarking on a new Bootstrap website project has presented me with a challenge that I have not been able to overcome, even with minimal HTML and just one flex item (which happens to be the only element on the site): <!DOCTYPE html> <html lang=" ...

Javascript: Harnessing Textbox Arrays for Improved Functionality

Check out the form displayed below. <form id="upload_form" enctype="multipart/form-data" method="post"> <input type="text" name="name[]" id="name"><br> <input type="text" name="name[]" id="name"><br> <input type="fil ...

Exploring Laravel 4: Navigating Tables with Relational Models

Edit: error fixed I am managing two interconnected Models: Project and Task. Their relationship is defined as follows: Project.php class Project extends Eloquent { public function tasks() { return $this->hasMany('Task'); ...

Using jQuery on a pair of events

I want to enhance this jQuery function so that it executes both on page load and when the window is resized. jQuery(document).ready(function() { Maybe something along the lines of: jQuery(document).ready OR $(window).resize(function() { ...

What is causing my navbar's 'ol' element to have a wider width than the

Hello, I have a navigation bar with a dropdown menu using ol. However, when I hover over the list items, the width of the list exceeds that of the ol element. I believe this is due to the white-space: nowrap CSS property, but I want the text in the dropdow ...

The final section of this code is failing to process PHP forms

My current project involves developing a form in PHP that fetches values from a database. The first code block, which checks for the existence of a value using if (!isset($_POST['nieuweBest'])), is functioning correctly. The second code blo ...