Home > database >  Onclick buttons to move an element to different positions
Onclick buttons to move an element to different positions

Time:11-15

I am trying to move an element (eg. an image) to three different positions, when different divs are clicked.

eg. if Button 01 is clicked, padding-left=0px is added to the image.

eg. if Button 02 is clicked, padding-left=30px is added to the image.

eg. if Button 03 is clicked, padding-left=60px is added to the image.

State 01

enter image description here

State 02

enter image description here

State 03

enter image description here

This is my first attempt, but is not moving the image.

$('#cardEN').on('click', function() {
  $('.logo').removeClass('en');
  $(this).addClass('en');
});

$('#cardCN').on('click', function() {
  $('.logo').removeClass('cn');
  $(this).addClass('cn');
});

$('#cardAR').on('click', function() {
  $('.logo').removeClass('ar');
  $(this).addClass('ar');
});
img {
  width: 100px;
}

.logo {
  padding-left: 0px;
}

.en {
  padding-left: 0px;
}

.cn {
  padding-left: 30px;
}

.ar {
  padding-left: 60px;
}

.nav {
  padding-top: 100px
}

.button {
  display: inline-block;
  text-align: center;
  margin-left: 20px;
  width: 50px;
  border: 1px solid black;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ><img src="https://images.pexels.com/photos/1114318/pexels-photo-1114318.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" /></div>


<div >
  <div  id="cardEN">Button 01</div>
  <div  id="cardCN">Button 02</div>
  <div  id="cardAR">Button 03</div>
</div>

CodePudding user response:

You need to add (and remove) classes to .logo. $(this) is refering to the clicked button not the .logo element, see below:

$('#cardEN').on('click', function() {
  $('.logo').addClass('en').removeClass('cn ar');
});

$('#cardCN').on('click', function() {
  $('.logo').addClass('cn').removeClass('en ar');
});

$('#cardAR').on('click', function() {
  $('.logo').addClass('ar').removeClass('cn en');
});
img {
  width: 100px;
}

.logo {
  padding-left: 0px;
}

.en {
  padding-left: 0px;
}

.cn {
  padding-left: 30px;
}

.ar {
  padding-left: 60px;
}

.nav {
  padding-top: 100px
}

.button {
  display: inline-block;
  text-align: center;
  margin-left: 20px;
  width: 50px;
  border: 1px solid black;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ><img src="https://images.pexels.com/photos/1114318/pexels-photo-1114318.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" /></div>


<div >
  <div  id="cardEN">Button 01</div>
  <div  id="cardCN">Button 02</div>
  <div  id="cardAR">Button 03</div>
</div>

  • Related