Reputation: 1
I gave my link a an id where if I click the link, I want my javascript to adjust the background image. I made a js-fiddle of a simple version of what I want here:
https://jsfiddle.net/qp8d390b/
<body background="http://www.blueskiescareers.co.uk/wp-content/uploads/2014/05/blue-sky-clouds.jpg">
<li>
<a id = "attempt1" href="#top">SNOOPY1</a>
</li>
<li>
<a>SNOOPY2</a>
</li>
<li>
<a>SNOOPY2</a>
</li>
<div id= "#top">TOP PART </div>
</body>
$(document).ready(function() {
$("a[id='attempt1']").click(function(e) {
e.preventDefault();
alert('works');
document.body.background = "https://upload.wikimedia.org/wikipedia/commons/0/02/Fried_egg,_sunny_side_up.jpg";
});
});
I'm new to selecting with javascript. Any help would be appreciated!
Upvotes: 0
Views: 40
Reputation: 695
You should use id-selector
in this case
https://api.jquery.com/id-selector/
$("#attempt1")
The selector you used which is attribute selector
is more used in inputs than in links (a
elements)
https://api.jquery.com/attribute-equals-selector/
You can find more info on jQuery selectors in
https://api.jquery.com/category/selectors/
Hope it helps
Upvotes: 0
Reputation: 337560
Firstly your HTML is invalid; li
must be in either a ul
or ol
and all a
elements must have either a name
or href
attribute.
Secondly, jQuery uses CSS rules, so to select by id is $('#attempt1')
.
Lastly, to change the background
CSS property to an image the URL string should be wrapped in url()
. Try this:
$(document).ready(function() {
$("#attempt1").click(function(e) {
e.preventDefault();
$('body').css('background', 'url("https://upload.wikimedia.org/wikipedia/commons/0/02/Fried_egg,_sunny_side_up.jpg")');
});
});
Upvotes: 1