Home › Forums › JavaScript › How can I add a new class into a div in Js?
- This topic is empty.
-
AuthorPosts
-
May 8, 2017 at 3:04 am #254643AyalaParticipant
Hi,
https://codepen.io/Ayalann/pen/WjXqYV
I want to add the class “.visible” into the div with id “text” when I click on the input.
So what I want: The text is hide until I click on the input. The text should be visible only when the input is on focus.
May 8, 2017 at 3:45 am #254644AtelierbramParticipantFirst you want to include the jQuery library in the demo: behind the gear icon, in the javascript tab.
$( "#input" ).focus(function() { $('#text').addClass('visible'); }); $( "#input" ).focusout(function() { $('#text').removeClass('visible'); });
My fork of your demo:
May 8, 2017 at 4:07 am #254645AyalaParticipantIt is beautiful! Thank you!
May 8, 2017 at 4:13 am #254646AtelierbramParticipantYour welcome. Since you are using jQuery, it’s API can help you out with these helper functions and it’s syntax. Examples on each of those as well: api.jquery.com
May 8, 2017 at 5:43 am #254649AyalaParticipantGood website, thanks!
May 11, 2017 at 2:31 pm #254755processprocessParticipantYou do not need JQuery for this. You can achieve this easily with pure JS.
It’s a little more code to write, however your app will load faster because the user does not have to download JQuery.const input = document.querySelector('#input'); const text = document.querySelector('#text'); input.addEventListener('focus', () => text.classList.toggle('visible')); input.addEventListener('blur', () => text.classList.remove('visible'));
May 11, 2017 at 3:34 pm #254759AtelierbramParticipantKudos for the ES5 syntax. Totally agree with not needing large frameworks for basic Dom manipulation.
One thing to keep in mind though is “how to best help the original poster’; like here Ayala is clearly a beginner, having enough trouble as it is with jQuery, but that’s not a bad place to start dipping your toes in.You can achieve this easily …
You make it look easy, but that IMO is the difficult part.
May 11, 2017 at 3:54 pm #254761processprocessParticipantMy bad, I should never use language about difficulty. That’s all subjective and I struggle every day, this stuff isn’t easy.
Core JS is becoming so powerful! Seems like a good chance to start people off with it!
OP, this might be a more readable syntax:
const input = document.querySelector('#input'); const text = document.querySelector('#text'); input.addEventListener('focus', function() { text.classList.toggle('visible'); }); input.addEventListener('blur', function() { text.classList.remove('visible'); });
The arrow’s in the earlier example is purely a shorthand syntax, but it makes for faster coding!
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.