Reputation: 11
I needed to update this to jQuery and i think i got everything but it isnt working, the only thing i can think of is the doc.body.style.back sections arent right but i dont know the proper format for jQuery. Can anyone help please?
$(document).ready(function() {
let clicker = $('#jeffery');
clicker.on('click', clickHandler);
function clickHandler(e) {
document.body.style.background = 'url("jefferyBig.jpg")';
}
}
$(document).ready(function() {
let clicker1 = $('#eagles');
clicker1.on('click', clickHandler1);
function clickHandler1(e) {
document.body.style.background = 'url("eaglesBig.jpg")';
}
}
$(document).ready(function() {
let clicker2 = $('#wentz');
clicker2.on('click', clickHandler2);
function clickHandler2(e) {
document.body.style.background = 'url("wentzBig.jpg")';
}
}
$(document).ready(function() {
let clicker3 = $('#jenkins');
clicker3.on('click', clickHandler3);
function clickHandler3(e) {
document.body.style.background = 'url("jenkinsBig.jpg")';
}
}
$(document).ready(function() {
let clicker4 = $('#cox');
clicker4.on('click', clickHandler4);
function clickHandler4(e) {
document.body.style.background = 'url("coxBig.jpg")';
}
}
Upvotes: 1
Views: 46
Reputation: 337560
You can use the css()
method to update the background image. You can also make the code DRY by placing the image src in a data-*
attribute on the element to click. Then you can group all the required elements with a class and have a single event handler:
$(document).ready(function() {
$('.bg-trigger').click(function() {
$('body').css('background-image', `url("${$(this).data('src')}")`);
});
});
<div class="bg-trigger" data-src="jefferyBig.jpg">Jeffery</div>
<div class="bg-trigger" data-src="eaglesBig.jpg">Eagles</div>
<div class="bg-trigger" data-src="wentzBig.jpg">Wentz</div>
<div class="bg-trigger" data-src="jenkinsBig.jpg">Jenkins</div>
<div class="bg-trigger" data-src="coxBig.jpg">Cox</div>
The advantages of this method is that the JS code is simplified, and also it's infinitely extensible without having to touch the JS code. To add options, you just create new HTML elements with the appropriate class
and data
attributes.
Upvotes: 0
Reputation: 1782
Here is a working example
$(document).ready(function() {
$('body').css('background-image', 'url(https://www.w3schools.com/html/pulpitrock.jpg)');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 0
Reputation: 65808
You use the .css() method:
$(body).css("background", "url('eaglesBig.jpg')");
And, as others have pointed out, you don't need multiple document.ready()
functions - you can combine all the code you want to run as soon as the DOM is ready into one .ready() function. Also, your current code doesn't have all the necessary }
syntax, so check that too.
Upvotes: 2