Cited a test example from the site for convenience. It seems to be all the rules: pressing the basket button and the appearance of the counter of goods. After reloading the page on the site, there will be no button or counter (because in the css, the counter of goods "num" display: none). Please help, how to implement a condition check: if the counter element is visible, then hide the button, otherwise, show the add to cart button

$('.add2cart').click(function(e) { e.preventDefault(); $(this).hide(); $(this).prev('.num').show(); }); 
 .num { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="num" type="number" placeholder="ΠΊΠΎΠ»-Π²ΠΎ"> <a class="add2cart" href=""> <img src="https://d30y9cdsu7xlg0.cloudfront.net/png/38919-200.png" alt=""> </a> 

I tried to make this condition:

 if ( $( ".add2cart" ).length ) { $( ".num" ).show(); } else { $( ".num" ).hide(); } 

Raised to the main page by a community spirit member ♦ 2 days ago .

This question contains answers that can be both good and bad; the system offered them for verification.

  • ПослС ΠΏΠ΅Ρ€Π΅Π·Π°Π³Ρ€ΡƒΠ·ΠΊΠΈ страницы Π½Π° сайтС ΡƒΠΆΠ΅ Π½Π΅ Π±ΡƒΠ΄Π΅Ρ‚ Π½ΠΈ ΠΊΠ½ΠΎΠΏΠΊΠΈ - well, yes, the button itself disappears. - Rustam Gimranov

2 answers 2

If you need to make sure that the block does not have CSS properties display:none , then the following code will do:

 $(function(){ console.log($('.num').css('display')=='none'?'Π”Π°, ΠΎΠ½ Π½Π΅Π²ΠΈΠ΄Π΅ΠΌ!':'Π‘Π»ΠΎΠΊ Π²ΠΈΠ΄ΠΈΠΌΡ‹ΠΉ') }) 
 .num{ display:none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="num"></div> 

Under your task:

 let button=$('button') if($('.num').css('display')=='none') button.show() else button.hide() 

If you still substitute your selectors:

 let button=$('.num') if($('.add2cart').css('display')=='none') button.show() else button.hide() 
  • such a condition is necessary. if the counter element is visible, then hide the button, otherwise - show the add to cart button - stiv
  • @StepanIvanov is the same if and else to substitute: let button=$('button') if($('.num').css('display')=='none') button.show() else button.hide() - Diskyp
  • Changed the answer, it looks prettier there. - Diskyp

If the css is

 .add2cart{ display: none; } 

Then enough

 $(function(){ if($('.num:visible').length > 0) $('.add2cart').fadeIn(); }); 
  • It is better not to use DOM mutation events; they have been removed from the standard: developer.mozilla.org/en-US/docs/Web/Guide/Events/… - Diskyp
  • Now we have to use bulky observers. - Diskyp
  • @Diskyp thanks, I will know - goodmice
  • If this is not worth it, then how is it better to register it? - stiv
  • @StepanIvanov can then be put in css or added to js "else $ ('. Add2cart'). FadeOut ();" - goodmice