1

I was wonder if there was a way to change a background image with a button click. The body background for my master page is in my external CSS sheet. I am not sure that this can be done with c#. My css code is like this.

body{
background-image: url(/images/image.jpg)
} 

I have updated my code, however it is not working correctly the image does not stay changed it flickers the new pic for a second but doesnt change it.

$(document).ready(function () {
            $('#Button2').click(function () {
                $('body').css('background-image', 'url(/Image/image.jpg)')
            });
        });
J.Doe
  • 23
  • 6

3 Answers3

2

ASP.NET renames the ID's of Controls when using a Master page. So depending of where the javascript function is you need to use ClientID

If the script is on the child page along with the button you do this

$('#<%= ButtonChild.ClientID %>').click(function () {

If the button is on the master, but the script is on the child you have to navigate up the control tree

$('#<%= Master.FindControl("ButtonMaster").ClientID %>').click(function () {

And when a button is clicked it will trigger a PostBack, so you might want to add return false;

<script type="text/javascript">
    $('#<%= ButtonChild.ClientID %>').click(function () {
        $('body').css('background', 'url(/images/image.jpg)');
        return false;
    });
</script>
VDWWD
  • 35,079
  • 22
  • 62
  • 79
0

Make sure you're referencing your button correctly through jQuery (use a # for id references).

$('#button1').click(function() { 
   $('body').css('background','url(/images/image.jpg)') 
});
DiscoInferno
  • 142
  • 1
  • 10
0
$('button1').click(function() {
('body').css('background-image','url(/images/image.jpg)')
}

its a duplicate question to the following question:

Changing background image using jquery
Community
  • 1
  • 1
Biswabid
  • 1,378
  • 11
  • 26
  • My code is not working correctly the background doesnt stay changed it just flickers and briefly shows the image it is supposed to change to. Here is my code:$(document).ready(function () { $('#Button2').click(function () { $('body').css('background-image', 'url(/Image/image.jpg)') }); }); – J.Doe Apr 29 '17 at 16:07