learningbyexample learningbyexample - 4 months ago 13
jQuery Question

Why does my image button not open the link that it should?

I have this code that should allow me to do what I do in the snippet. It works in the snippet but it does not work in my local php file.

I have the jquery library and everything calls correctly but the image that i'm using is not activating the input file type that should be comming out as it is in the snippet.



$('.image-upload-btn').on('click', function() {
var input = document.createElement('INPUT');
input.type = 'file';
input.style.display = 'none'
$('html body').append(input);
input.click();
input.onchange = function() {
$('.image-upload-btn').css('background-image', 'url(http://icons.iconarchive.com/icons/martz90/circle/512/camera-icon.png)');
}
});

.image-upload-btn {
background-image: url('http://bread.pp.ua/n/settings_g.svg');
background-position: center;
background-size: cover;
width: 50px;
height: 50px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class='image-upload-btn'></div>





<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$('.image-upload-btn').on('click', function(){
var input = document.createElement('INPUT');
input.type = 'file';
input.style.display = 'none'
$('html body').append(input);
input.click();
input.onchange = function(){
$('.image-upload-btn').css('background-image', 'url(http://icons.iconarchive.com/icons/martz90/circle/512/camera-icon.png)');
}
});
</script>
<style type="text/css">
.image-upload-btn{
background-image: url('http://bread.pp.ua/n/settings_g.svg');
background-position: center;
background-size: cover;
width: 50px;
height: 50px;
}
</style>
<div class='image-upload-btn'></div>

Answer

probably the html loaded after the jquery bind, try this

$(document).ready(function(){  

  $('.image-upload-btn').on('click', function() {
    var input = document.createElement('INPUT');
    input.type = 'file';
    input.style.display = 'none'
     $('html body').append(input);
     input.click();
     input.onchange = function() {
     $('.image-upload-btn').css('background-image', 'url(http://icons.iconarchive.com/icons/martz90/circle/512/camera-icon.png)');
    }
  });

});