5

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>
Michail Michailidis
  • 11,792
  • 6
  • 63
  • 106

6 Answers6

4

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

Michail Michailidis
  • 11,792
  • 6
  • 63
  • 106
  • Don't I have to change the html anything? This seemes like a good solution but the only problem is you cant click on the div, since it's not a link or anything – Alice Holmer Lazar Feb 14 '16 at 15:41
  • you can put click to anything it doesn't have to be a link ;) you can change your cursor to be pointer if you want it to appear as clickable – Michail Michailidis Feb 14 '16 at 15:42
  • @AliceHolmerLazar I updated the answer so you can change the cursor on :hover to be a pointer – Michail Michailidis Feb 14 '16 at 15:45
  • 2
    Wait, this changes the background of the button, not the body? – Alice Holmer Lazar Feb 14 '16 at 15:52
  • Thanks @KaiChristensen – Michail Michailidis Feb 14 '16 at 16:06
  • This was very helpful! It doesn't work yet, maybe becauise of something I have mistyped or missed, but this made sense even to me, a total beginner with jquery. :) – Alice Holmer Lazar Feb 14 '16 at 16:49
  • Would you mind if I shared the files with you so you could have a look? It feels like it's supposed to work – Alice Holmer Lazar Feb 14 '16 at 17:00
  • 1
    @AliceHolmerLazar most probably you forgot to put the binding of on click event after html has finished rendering (```$(document).ready```) - added it in the answer - check my plunkr and let me know if more help is needed :) – Michail Michailidis Feb 14 '16 at 18:30
  • @MichailMichailidis May be helpful to OP to describe difference between approaches of using `.addClass()` and `.toggleClass()`; where plnkr uses `.toggleClass()` though Answer uses `.addClass()` – guest271314 Feb 14 '16 at 18:36
  • 1
    @guest271314 those are very well documented (https://api.jquery.com/addclass/ & https://api.jquery.com/toggleclass/) - and if you have seen I had already a comment in the code- I am expecting the OP to express any further questions she might have otherwise my answer would be too long and not very useful. – Michail Michailidis Feb 14 '16 at 18:40
  • @AliceHolmerLazar I added an extra plunkr that circulates over a fixed collection of backgrounds defined in css using the same code structure :) – Michail Michailidis Feb 14 '16 at 19:04
  • hm this made less sense to me, but i have several problems with the code, not only in tje jquery file. i problably screwed up from the start. here's a link to the files if anyone wants to check them out: https://plnkr.co/edit/?p=catalogue – Alice Holmer Lazar Feb 14 '16 at 20:48
  • @AliceHolmerLazar you need to save the link so it has an id and we can see it – Michail Michailidis Feb 14 '16 at 20:55
  • @AliceHolmerLazar https://plnkr.co/edit/ZVjWbepxKcBnmMs7ZOaj?p=preview here it is working.. you had local style and script urls and no jquery in the plunkr html. also your clickable div was empty so I added some red text. your script had a mistake too. Make sure the plunkrs you will be making in the future don't have local urls.. since those won't work - everything needs to be local to plunkr :) – Michail Michailidis Feb 14 '16 at 21:22
  • it's working, kind of. now, when i load the page there is no bg. but atfer i press the button it starts to toggle – Alice Holmer Lazar Feb 14 '16 at 22:04
  • @AliceHolmerLazar did you put bg-0 class on body so it has background for the first time? My plunkr has background the first time. – Michail Michailidis Feb 14 '16 at 22:10
3
  1. Create a button with onclick attribute with a function name like replace.
  2. Defined the function in your script like:

    function replace() {
       document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)';  
    }
    

Explanation:

You set the style property of the body (using document.body object) to other background-image.

If something is not clear, I will happy to explain.

Working example:

function replace() {
  document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)';  
}
body {
  background-image: url(http://www.julienlevesque.net/preview/google-smile-preview.jpg);
}

div {
  background:blue;
  color:#fff;
  float:left;
}
<div onclick="replace()">Replace background-image</div>
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
1

If I understand the question, you should be able to create a variable in jQuery which is an array of all the string versions of your image urls that you want to use:

var images = ['../images/####','../images/$$$$', 'http://some.other/url.here];

// do this for as many images as you want to cycle through

Like that.

Then you can make a counter variable:

var counter = 0;

and set it to zero.

Next, add the event listener on() to your div like this:

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



});

Finally, inside your event listener, change the CSS background-image property of the div to one of your images in the array:

// do this inside a document.ready() function
$('#knapp').on('click', function(){

    $(this).css('background-image','url("' + images[counter] + '")');
    counter++;

});

I hope this helped! Also, remember to increment counter

EDIT ----------------------------------------------------------------

OK, so I totally jumped over something obvious which is the fact that the counter might go too high and access something out of scope. To prevent this add the following inside of your on() listener:

if(counter >= images.length - 1){

    counter = 0;

}

EDIT 2 --------------------------------------------------------------

Ok, so I didn't know what exactly you were asking at first, so here is my second answer. Since it seems like what you are actually trying to do is only switch the background image once on click, then you could use something like this:

$(document).ready(function(){

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

        $(this).css('background-image','url("YOUR_NEW_URL_HERE")');

});

});

or you could have it toggle between two images by making two identical classes in CSS (except for the background image) and replacing one with the other using .addClass and .removeClass.

EDIT 3---------------------------------------------------------------

I never thought I would edit this post this many times, but apparently I missed that the body background image should be changed (thanks to comments). My bad and thanks for pointing it out (even if you were talking to someone else).

kairocks2002
  • 436
  • 1
  • 3
  • 15
  • I added your circular background idea to an extra plunkr! Thanks – Michail Michailidis Feb 14 '16 at 19:01
  • Thanks for the help Kai although I went with the other suggestion since it seemed easier and more logical. https://plnkr.co/edit/eOClcBGhKPz2UoS8oHXm?p=catalogue here's the result. Still doesn't work. I must have done something wrong from the start – Alice Holmer Lazar Feb 14 '16 at 20:53
1

This may help you...

$('.yourClassofDiv').click({
   $(this).css("background-image",'url("' + URLofIMAGE+ '")')
});
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
1

Try using onclick at div#knapp element , set document.body.style.background to url of image file

#knapp {
  height:50px;
  width:50px;
  background-image:url(http://lorempixel.com/50/50);
  background-repeat:no-repeat;
  background-size:contain; 
  position:absolute;
  top:90vh;
  right:3vw;
}
<div id="knapp" class="grid-10 prefix-90" onclick="document.body.style.background = 'url(http://lorempixel.com/'+ window.innerWidth + '/'+ window.innerHeight +') no-repeat'"></div>
guest271314
  • 1
  • 15
  • 104
  • 177
  • this answer while concise couples javascript with html and css ..so I believe is not a good idea for a new developer to start with bad technique from day one. – Michail Michailidis Feb 14 '16 at 15:39
  • 1
    @MichailMichailidis you can't downvote just because you `believe is a bad practice`. Please comment and let the user to explain you his thoughts.. – Mosh Feu Feb 14 '16 at 15:41
  • I don't believe - it is a very bad practice – Michail Michailidis Feb 14 '16 at 15:45
  • @MichailMichailidis Version separating `js` from `html` plnkr http://plnkr.co/edit/GS9Bysy7trku1MvRN7SZ?p=preview – guest271314 Feb 14 '16 at 15:46
  • @guest271314 you are still using js to change style directly - which for this small example is really not needed - your plunkr is making js do what css's job is to do – Michail Michailidis Feb 14 '16 at 15:48
  • @MichailMichailidis _"I don't believe - it is a very bad practice"_ In your opinion, is all use of `on` event handlers within `html` "very bad practice" ? – guest271314 Feb 14 '16 at 15:48
  • @MichailMichailidis _"you are still using js to change style directly - which for this small example is making js do what css should do"_ ? Should a `css` only approach be used ? – guest271314 Feb 14 '16 at 15:49
  • no it is not - it is an old practice at least 15 years old - that needs at some point to stop :) – Michail Michailidis Feb 14 '16 at 15:49
  • @MichailMichailidis _"no it is not - it is an old practice at least 15 years old - that needs at some point to stop :)"_ ? Is this a crusade ? Do you "downvote" every Answer at SO which includes `on`-event handlers in `html` ? – guest271314 Feb 14 '16 at 15:51
  • @guest271314 see my example I use js to just add a class - and css takes care of what that means.. makes the code more flexible more concise and separates all the concerns of structure (html), presentation(css) and behavior(js) – Michail Michailidis Feb 14 '16 at 15:51
  • @MichailMichailidis If you make an argument about using `js` within `html` , it is only fair to point out that your solution loads an entire library (jQuery) to use `.on()` ? How is loading an entire library to attach an event not "bad practice" ? – guest271314 Feb 14 '16 at 15:52
  • @guest271314 not really I don't have that much free time - I just did because reputation tends to be connected with more experience and more correct answers. This is a new developer that if he starts using bad practices from day one he will continue those 10-15 year old techniques when he goes to work for a company – Michail Michailidis Feb 14 '16 at 15:54
  • @MichailMichailidis fwiw, using event handlers within `html` is not deprecated. What does working for a company have to do with the present Question ? – guest271314 Feb 14 '16 at 15:54
  • 1
    @MichailMichailidis Also note, your posted solution does not change the `background` of `body` element ? See OP at _"to change the body background-image"_ Perhaps "downvote" yourself ? – guest271314 Feb 14 '16 at 15:56
  • 1
    @MichailMichailidis Curious, what is the source, reference of the phrase _"it is a very bad practice"_ ? Or is this your opinion ? – guest271314 Feb 14 '16 at 16:00
  • Some random sources that are basically hundreds but we are in stackoverflow: http://philipwalton.com/articles/decoupling-html-css-and-javascript/, http://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice, http://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice http://stackoverflow.com/questions/98734/what-is-separation-of-concerns etc – Michail Michailidis Feb 14 '16 at 16:05
  • @MichailMichailidis The phrase _"it is a very bad practice"_ does not appear at linked pages ? – guest271314 Feb 14 '16 at 16:08
  • @guest271314 drop "very" if that makes you happy. I don't have time to play with words – Michail Michailidis Feb 14 '16 at 16:11
  • @MichailMichailidis _"drop "very" if that makes you happy. I don't have time to play with words"_ ? Those are _your_ words. Seeking to affirm correct attribution for the phrase _"it is a very bad practice"_ . No games or "play", whatsoever, here. Not about "happy"; you begat this exchange; only attempting to clarify the source of your posted comment. At present, would have to attribute _"it is a very bad practice"_ to you – guest271314 Feb 14 '16 at 16:13
  • @guest271314 can you find me a single source that says that your practice is good? I gave four sources and I can send way more that indicate that your code is towards practices that lead to problems. – Michail Michailidis Feb 14 '16 at 16:21
  • @MichailMichailidis _"can you find me a single source that says that your practice is good?"_ The original Question is not about whether or not including inline event handlers within `html` is a "good" or "bad" practice. – guest271314 Feb 14 '16 at 16:24
  • @guest271314 you must be a part-time lawyer - I would like to spend more time on coding and reading good practices books than arguing about words – Michail Michailidis Feb 14 '16 at 16:25
  • 1
    @guest271314 I have seen a lot of applications, costing millions to make thrown away, using similar coding practices that made the technical debt unsustainable. Bad code eventually costs a LOT of money, I hope you agree with that at least – Michail Michailidis Feb 14 '16 at 16:33
1

here is a simple way in jquery

$(document).ready(function() {
  $("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat');
  $('div').css('cursor', 'pointer').click(function() {
        $("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body>
  <div style="background-color:yellow">Click Here to change background Image</div>
</body>

Here i will explain the code. The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).

Basic syntax is: $(selector).action()

A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

Here is what happen in the code.

1.

$(document).ready(function(){

   // jQuery methods go here...

}); 

This is to prevent any jQuery code from running before the document is finished loading (is ready).It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.

2

$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat');

getting the body element of your html and set its background-image with .css() action. which i gave it more one action

3

$('div').css('cursor', 'pointer').click(function() {
        $("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)');
    });

this is where the change takes place. i got the div to be clicked by $('div') and first gave it an action of changing the mouse to cursor to indicate its clickable and then gave it the click function, where our background-image get changed on click

Transformer
  • 3,642
  • 1
  • 22
  • 33