HTML and CSS Reference
In-Depth Information
</style>
</head>
<body>
<div id=ad>
<section>
<div id=close>X</div>
<div id=cta class=button>Click Here</div>
</section>
</div>
</body>
</html>
<script>
var ad = document.querySelector('#ad');
var cta = document.querySelector('#cta');
var close = document.querySelector('#close');
cta.addEventListener('click', expandAd, false);
close.addEventListener('click', collapseAd, false);
function expandAd () {
ad.style.width = '500px';
cta.style.left = '360px';
close.style.opacity = 1;
}
function collapseAd () {
ad.style.width = '300px';
cta.style.left = '160px';
close.style.opacity = 0;
}
</script>
If you've followed along, keep a close eye on the boldface sections of the Listing 5-9 code. In its CSS,
transition:
all 1s ease-in-out;
has been added to all the elements to be moved—in this case, our ad, our CTA, and our
new Close icon. In the HTML markup, a new
div
element is added inside our section container by writing
<div
id=close>X</div>
. This is what will close the expanded ad experience. Finally, take a look at the JavaScript toward
the end of the listing's code. The minimal JavaScript code first declares variables to reference the objects in our DOM.
In this case, it's our ad, the CTA button, and the new Close icon. Next, event listeners are added for the user's mouse
click by writing
cta.addEventListener('click', expandAd, false);
and
close.addEventListener('click',
collapseAd, false);
. Doing this allows handling the user's action appropriately and calls
expandAd
and
collapseAd
,
respectively. Inside the
expand
method the ad's width is expanded to 500 pixels, the button is moved on its
left
property, and the Close icon's opacity is toggled by setting it to a value of 1. (The opacity property is another almost
finalized feature in the CSS3 specification; it gives the ability to adjust the fill of an element or image between 0 and 1.)
Conversely, the ad is reset to its original setting by calling the
collapseAd
function. Figure
5-9
shows what you'll get in
the browser if you click on the CTA button.