Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

div onclick function to change body background image

I want a small picture that acts like a button, to be click-able with a function to change the body background-image. I am a total newbie and I'm trying to learn. The most simple way, I thought, would be to have a div with a background-image. I have to use unsemantic grid, also.

So I pretty much only have the div with a background image. How do I write this function? I'm sure it's really easy and I've read like 20 threads here but none of them were useful for me

Edit: added my code

#knapp {
  height:50px;
  width:50px;
  background-image:url(http://ingridwu.dmmdmcfatter.com/wp-content/uploads/2015/01/placeholder.png);
  background-repeat:no-repeat;
  background-size:contain;	
  position:absolute;
  top:90vh;
  right:3vw;
}
<div id="knapp" class="grid-10 prefix-90"></div>
like image 477
Alice Holmer Lazar Avatar asked Feb 14 '16 15:02

Alice Holmer Lazar


1 Answers

Add cursor on the div to appear clickable

   #knapp {
      cursor: pointer;
   }

You could put the new background-image in a new css rule

body.newbg {
    background-image:url(path-to-new-background.png);
}

This is body with the old background-image

body {
    background-image:url(path-to-old-background.png);
}

and with jquery just add/toggle the class by doing something like that (in $(document).ready()):

$('#knapp').on('click', function(){

    $('body').addClass('newbg');
    // you could instead do toggleClass if you want for each click to have background switch between old background and new background
});

This is a cleaner approach compared to all the other answers as it separates presentation (css), structure (html) and behavior (javascript). This is because it doesn't use JavaScript to change style directly. Also it doesn't pollute html with onclick which is also a bad practice.

Here is a plunkr: https://plnkr.co/edit/aiGZmvvi6WWGFs7E9xTp

and here is one with a circular collection of backgrounds (thanks to Kai's idea) https://plnkr.co/edit/0djmmNM9OOTdfYyvLvUH?p=preview

like image 193
Michail Michailidis Avatar answered Sep 20 '22 19:09

Michail Michailidis