I basically want to make that when I press on a button the first time it adds display: none; to an element and when I press it again it makes the element appear again (so add display: none;). How would I do this with jQuery?
This is the jQuery I tried to implement but as I'm new to Javascript I don't know why it isn't working.
$('#menuBtn').click(function() {
var clicks = $(this).data('clicks');
if (clicks) {
$('.header-text').css({
'display': 'none'
});
} else {
$('.header-text').css({
'display': 'block'
});
}
$(this).data("clicks", !clicks);
});
Use toggle or slideToggle (With animation)
$('#menuBtn').on('click', function() { $('.header-text').toggle(); }); $('#menuBtnSlide').on('click', function() { $('.header-text').slideToggle(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="menuBtn">Toggle</button> <button id="menuBtnSlide">SlideToggle</button> <div class="header-text"> This content must me show and hide </div>
You could supply a modifier class in some external stylesheet for hiding the text and toggle it via toggleClass .
Word of advice: It's best not to use something like toggle because it will inject inline css into your elements, making it difficult to override in the long-run for something so simplistic.
const $headerText = $('.header-text'); $('#menuBtn').click(function() { $headerText.toggleClass('header-text--hidden'); });
.header-text--hidden { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="menuBtn" type="button">Toggle</button> <header> <p class="header-text">Text 1</p> <p class="header-text">Text 2</p> <p class="header-text">Text 3</p> <p class="header-text">Text 4</p> </header>
You actually don't need jQuery for this.
You can add CSS rule to set .hidden
to display: none
and then toggle that class when the button is clicked.
To catch the click event on the button, you need a click event listener
const header = document.querySelector('.header'); const toggle = document.querySelector('.menu-toggle'); toggle.addEventListener('click', () => { header.classList.toggle('hidden') });
.header { background: red; height: 3em; } .hidden { display: none; }
<header class="header"></header> <button class="menu-toggle">Click me!</button>
.hidden{display:none !important;}
$('#menuBtn').click(function() {
$('.header-text').toggleClass("hidden");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.