Find and open your JSFiddle link from last time.
We're going to be using a library called jQuery to help us do things better in JavaScript. If you look at the top left of JSFiddle there should be a drop down of libraries you can use - you might need to look fo a while to find jQuery 2.1.0.
Next, we have to give an id
to all the shapes that we're going to make interactive - i've given my emoji face an an id
of face:
<circle cx="300" cy="300" r="200" fill="url(#radialGrad)" id="face" />
We can then use that id using jquery to make a variable - a variable is just a "thing with a name" - for example our sun shape is the thing with the name of faceShape
.
var faceShape = $("#face");
the $
means we're using jQuery.
the #
means find the object with the following name.
Now we have a variable - we can do things to it. We're going to add a "click listener" - this means it'll just listen for any clicks on the face circle.
faceShape.click(function() {
alert("clicked the face");
});
We've set up an alert to go when you click the face - click run and see what happens!
Now we're going to make it so that when you click on the face it changes the colour:
faceShape.click(function() {
faceShape.attr("fill", "#ffcc00");
});
This is just changing the fill
attribute to a different hex colour. Have a go at playing around with changing the r
value too...
Finally, we're going to make it so that when you click on the face it changes the colour, and then you can click to change it back again:
First, add a 'state variable' underneath the faceShape
variable. This is so the code can keep track of which shape has been chosen.
var isFacePink = true;
Then, add some "conditional code" into the click function. This allows the code to chose between different colours each time you click.
faceShape.click(function() {
if (isFacePink)
{
faceShape.attr("fill", "#ffcc00");
isFacePink = false;
} else
{
faceShape.attr("fill","pink");
isFacePink = true;
}
});
This is just changing the fill
attribute to a different hex colour. Have a go at playing around with changing the r
value too...
Have a go at making the conditional longer, by putting in more numbers. It's quite tricky, so please ask me show you how to do it.
Have a go at adding some interactivity into shapes such as the eyes - next time we're going to look at using logic to turn our shapes back to their original.
⭐ When you've finished - don't forget to save your JSFiddle and send us your link above. 🌟