Проблема работы if-else в JQuery

Всем привет! Я только начинаю изучать JS и JQuery. Сейчас я работаю над тем, чтобы при нажатии на блок с текстом он сдвигался на 150px вправо и менял цвет, а при повторном нажатии все возвращалось в прежний вид.

Но есть одна проблема: Когда я нажимаю первый раз - все работает, а когда повторно - ничего не меняется.

JS:

$('document').ready(function() {
    $('p').click(function() {

    if ($(this).css({'margin-left':'0px'})) {
      $(this).css({'margin-left':'150px'});
      $(this).css({'background-color':'orange'});
    } else {
      $(this).css({'margin-left':'0px'});
      $(this).css({'background-color':'yellowgreen'});
      console.log($(this).css('111'));
    }
  });
});

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    p {
      width: 150px;
      height: 150px;
      background-color: yellowgreen;
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      margin-left: 0;
    }
  </style>
</head>
<body>
    <p>Lorem ipsum dolor sit amet.</p>
  <p>Porro illum officia aperiam eos?</p>
  <p>Voluptatem obcaecati quo corrupti odit?</p>
  <p>Optio, dignissimos qui. Vero, nesciunt?</p>
  <p>Blanditiis autem magni omnis nam.</p>

  <script src="./js/jquery-3.5.1.js"></script>
  <script src="./js/script.js"></script>
</body>
</html>

Благодарю за помощь!


Ответы (3 шт):

Автор решения: Igor

Вызов $(this).css({'margin-left':'0px'}) возвращает jQuery объект-обертку, что соответствует булевскому true, так что в else код никогда не заходит.

$('p').click(function() {
  $(this).toggleClass('move-left');
});
p {
  width: 150px;
  height: 50px;
  background-color: yellowgreen;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  margin-left: 0;
}

.move-left {
  margin-left: 150px;
  background-color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet.</p>
<p>Porro illum officia aperiam eos?</p>
<p>Voluptatem obcaecati quo corrupti odit?</p>
<p>Optio, dignissimos qui. Vero, nesciunt?</p>
<p>Blanditiis autem magni omnis nam.</p>

→ Ссылка
Автор решения: Владлен Волков
$('document').ready(function() {
   $('p').click(function() {

   const marginLeftValue = $(this).css('margin-left');

   // если передать объект,
   // как в твоём коде [$(this).css({'margin-left':'0px'})]
   // то стили присваиваются, и возвращается сам элемент

   if (marginLeftValue === '0px') {
      $(this).css({'margin-left':'150px'});
      $(this).css({'background-color':'orange'});
   } else {
      $(this).css({'margin-left':'0px'});
      $(this).css({'background-color':'yellowgreen'});
      console.log($(this).css('111'));
   }
 });
});

Но как верно заметили в другом ответе/комментарие -> лучше это делать через класс.

→ Ссылка
Автор решения: highpassion

Предлагаю вам реализацию этих перемещений за счет проверки на присутствие класса в jQuery.

$('document').ready(function() {
    $('p').click(function() {
    
    if ($(this).hasClass("moved")) {
      $(this).removeClass("moved")
      $(this).css({'margin-left':'0px'});
      $(this).css({'background-color':'yellowgreen'});
    }

    else {
      $(this).addClass("moved")
      $(this).css({'margin-left':'150px'});
      $(this).css({'background-color':'orange'});
      // console.log($(this).css('111'));
    }  
  });
});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    p {
      width: 150px;
      height: 150px;
      background-color: yellowgreen;
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      margin-left: 0;
    }
  </style>
</head>
<body>
    <p>Lorem ipsum dolor sit amet.</p>
  <p>Porro illum officia aperiam eos?</p>
  <p>Voluptatem obcaecati quo corrupti odit?</p>
  <p>Optio, dignissimos qui. Vero, nesciunt?</p>
  <p>Blanditiis autem magni omnis nam.</p>

  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <!--<script src="script.js"></script> РАСКОММЕНТИРУЙТЕ ЭТУ СТРОКУ У СЕБЯ-->
</body>
</html>

→ Ссылка