StevenWalker StevenWalker - 1 year ago 62
Javascript Question

Why is jQuery.css() not working for me?

I've been struggling with some code and quite seem to get it to work - apologies if this is a silly question, I'm still quite new to JavaScript/jQuery etc.

I'm trying to build a Weather App as part of the Free Code Camp course and have built using simpleWeather.js. I'm now trying to animate a little bit of the page to make it a bit more interactive. I have some code:

$('#drop').on('click', function() {
$('.fa-chevron-circle-down').css('transform', 'rotate(180deg)');

I believe this should on a click, rotate the icon 180 degrees but no matter what variations I try, I can't seem to get it to work. After spending hours yesterday playing with it I decided it's time to ask for help! (The idea is that once it works, I'll animate the elements below so they only show when the button is clicked).

My codepen is

Thanks in advance for any help anyone can give.

Answer Source

Your #drop element has been created after DOM load i.e. dynamically. Hence you need event delegation here. So attach your click to document and then refer your element - #drop.

$(document).on('click','#drop', function() {
  $('.fa-chevron-circle-down').css('transform', 'rotate(225deg)');

Updated PEN

To be more simpler, since #weather element existed during DOM load, insted of document you can add it to #weather element. Consider below example.

$('#weather').on('click','#drop', function() {
  $('.fa-chevron-circle-down').css('transform', 'rotate(225deg)');

and also I believe, it should have been 180deg to be proper turn-around.

Updated PEN 2 with 180deg and #weather

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download