29.07.2016 Views

front-end-developer_1_

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Front-End-Developer - Level 1<br />

$(document).ready(function() {<br />

$("button#green").click(function() {<br />

$("body").removeClass();<br />

$("body").addClass("green-background");<br />

});<br />

$("button#yellow").click(function() {<br />

$("body").removeClass();<br />

$("body").addClass("yellow-background");<br />

});<br />

$("button#red").click(function() {<br />

$("body").removeClass();<br />

$("body").addClass("red-background");<br />

});<br />

});<br />

And now everything works perfectly!<br />

removeClass() without an argument removes all classes from the selected element; if you'd<br />

like to just remove a specific class, you can pass it in as an argument (or pass in multiple<br />

classes separated by spaces).<br />

There is another way to change the CSS of an element with jQuery:<br />

$("button#green").click(function() {<br />

});<br />

$("body").css("background-color", "green");<br />

You've seen this before, in my trick for making sure the correct element is selected.<br />

However, this is a bad approach for real code, for two reasons. First, it's mixing our<br />

concerns. JavaScript is responsible for how the page behaves; CSS is responsible for how<br />

the page looks. Here, we've put something about how the page looks in our JavaScript. This<br />

makes it difficult for other programmers who might need to change this page in the future to<br />

know where to look for the appropriate code. Second, you lose one of the biggest powers of<br />

CSS: the ability to create a class and re-use that style across elements and pages. Here,<br />

when we've put a style in our JavaScript, it can't be re-used. So, when you want to change<br />

the style of your page, stick to adding and removing classes.<br />

Before we move on from our intro to jQuery, you should take a look at the jQuery<br />

documentation. It will probably feel a bit overwhelming at first, and there is a lot in there we<br />

haven't even begun to cover. But check out the sections on Effects, Mouse Events, Form<br />

Events, Manipulation, and Traversing. There's a lot in there you'll be able to understand. And<br />

in the future, when you're trying to figure out how to do something with jQuery, the<br />

documentation is a great place to look.<br />

Attributes<br />

188

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!