It seems to me that you did not understand the task a bit. The code is executed once and not all the time. When you hide news, this is one action, and when it is completed, nothing actually happens. To show the news again, you need to run the script one more time, which will show the news.
For example, you put an event handler on the checkbox news :
$('#news').on('change', function(){ ...здесь ваш код... })
This script will be executed every time you put and uncheck the checkbox . And after execution, the browser will not execute any scripts until it receives the next event.
We do not need to write another event handler, we need to determine whether the check is pressed or not:
$('#news').on('change', function(){ if($(this).is(':checked')){ //галочка нажата, скрываем новости }else{ //галочка не нажата, показываем новости } })
Next we put your code:
$('#news').on('change', function(){ if($(this).is(':checked')){ //галочка нажата, скрываем новости $('.boxx').each(function(){ if($(this).find('a').hasClass('viewsfull')){ $(this).hide() } }) }else{ //галочка не нажата, показываем новости } })
And if we press for the second time, $("this").is(':checked') is no longer true, and there need to show the news, take the same code, but replace the hide() with show()
$('#news').on('change', function(){ if($(this).is(':checked')){ //галочка нажата, скрываем новости $('.boxx').each(function(){ if($(this).find('a').hasClass('viewsfull')){ $(this).hide() } }) }else{ //галочка не нажата, показываем новости $('.boxx').each(function(){ if($(this).find('a').hasClass('viewsfull')){ $(this).show() } }) } })
Working example:
$('#news').on('change', function() { if ($(this).is(':checked')) { //галочка нажата, скрываем новости $('.boxx').each(function() { if ($(this).find('a').hasClass('viewsfull')) { $(this).hide() } }) } else { //галочка не нажата, показываем новости $('.boxx').each(function() { if ($(this).find('a').hasClass('viewsfull')) { $(this).show() } }) } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input class="checkbox" type="checkbox" id="news" name="news" value="1"> <label for="news">Скрыть новости</label> <div class="boxx"><a href="#" class='viewsfull'>Новость</a> </div>
There is one more function that simplifies the script: toggle() It hides objects if they are visible and shows if they are hidden. Ie everything can be simplified to this:
$('#news').on('change', function(){ $('.boxx').each(function(){ if($(this).find('a').hasClass('viewsfull')){ $(this).toggle() } }) })
Pavel Mayorov also pointed out that it is easier to use the : has selector to immediately find blocks that have a link with a specific class:
$('#news').on('change', function(){ $('.boxx:has(a.viewsfull)').toggle() })