daviswader
daviswader

Reputation: 3

Can't change background image with JS/ Jquery

I have an input box that takes the web URL of any image and then i have a button that change the CSS background image. The code is good the way i look at it but it isnt working. Can you point out the fault.

HTML

<input name="webURL" type="text" id="webURL" value="" placeholder="Or paste a web URL"><br>
<input type="submit" id="submit-btn" class="webBtn" value="Upload it."/>

JS

$('.webBtn').click(function(){
    $('#uploadedPhoto').css('background-image', "url($('#webURL').attr('value'))");
    $('#webURL').attr('value', URL);
});

Upvotes: 0

Views: 528

Answers (4)

Ruprit
Ruprit

Reputation: 743

HTML

<input name="webURL" type="text" id="webURL" value="" placeholder="Or paste a web URL"><br>
<input type="submit" id="submit-btn" class="webBtn" value="Upload it."/>

<div id="uploadedPhoto" style="width:200px; height: 200px;"></div>

jQuery

<script>
    $('.webBtn').click(function(){
        var upUrl = $('#webURL').val();

        $('#uploadedPhoto').css({'background-image' : 'url(' + upUrl + ')','background-repeat': 'no-repeat'});
        $('#webURL').attr('value', URL);
  });
</script>

Try this. Should work.

Upvotes: 1

Rohit Suthar
Rohit Suthar

Reputation: 3628

Try this working code -

$('.webBtn').click(function(){
    $('#uploadedPhoto').css('background-image',"url("+$('#webURL').val()+")");
    $('#webURL').val('');
});

Demo - Fiddle

Upvotes: 0

user229044
user229044

Reputation: 239521

JavaScript doesn't do string interpolation.

This is a literal string containing a jQuery selector.

"url($('#webURL').attr('value'))"

Instead, you need to build the correct string up by concatenating the various parts:

"url(" + $('#webURL').attr('value') + ")"

Upvotes: 0

Nibin
Nibin

Reputation: 3960

Try this mate

$('.webBtn').click(function(){
        $('#uploadedPhoto').css('background-image',"url("+$('#webURL').attr('value')+")");
        $('#webURL').attr('value', URL);
    });

Fiddle

Upvotes: 1

Related Questions