Alex Underhill Alex Underhill - 3 months ago 8
HTML Question

Trying to change the position of a div when clicked using js

I'm editing a website for use on tablet, but obviously none of my :hover pseudo-classes will work.

I want to move a div up to reveal text by the same amount as when I hover, but I want it to happen when I click "up_down_icon.png".

Here is my html:

<div class="home_1">
<div class="h_1_text_box">
<h3>Our Concept</h3>
<img class="icon" src="up_down_icon.png">
<p>Text here</p>
</div>
</div>


And the CSS:

.h_1_text_box {
background-color: rgba(0, 0, 0, 0.5);
padding: 12px 16px 24px 16px;
color: #ffffff;
font-family: Franklin Gothic;
position: relative;
top: 255px;
transition: 0.5s ease;
}

.h_1_text_box:hover {
position: relative;
top: 171px;
background-color: rgba(0, 0, 0, 0.9);
}

.icon {
width: 24px;
height: 24px;
position: absolute;
top: 11px;
left: 560px;
transition: 0.5s ease;
}

.h_1_text_box:hover > .icon {
transform: rotate(-180deg);
}


Literally all I need to know is how to apply a change of position to .h_1_text_box, to be specific, moving it up 84px.

The answer is probably going to be really simple and I feel a little silly for asking, but my code is a bit long for me to get my head around applying JS. I haven't been able to find anything specific enough to help me out. If I have to change the order of anything in my HTML I don't mind.

Thanks for your help.

Answer

Just add an event listener to your icon which will listen for click events. Then you would just need to add a css class to the parent element. You already have everything you need in your css defined.

Here is an example.

var upDownIcon = document.getElementsByClassName('icon').item(0);

upDownIcon.addEventListener('click', function(e) {
	e.target.parentNode.classList.toggle('move_up_down');
}, false)
.h_1_text_box {
  background-color: rgba(0, 0, 0, 0.5);
  padding: 12px 16px 24px 16px;
  color: #ffffff;
  font-family: Franklin Gothic;
  position: relative;
  top: 100px;
  transition: 0.5s ease;
}

.h_1_text_box.move_up_down {
  position: relative;
  top: 0px;
  background-color: rgba(0, 0, 0, 0.9);
}

/*
.h_1_text_box:hover {
position: relative;
top: 171px;
background-color: rgba(0, 0, 0, 0.9);
}
*/

.icon {
  width: 24px;
  height: 24px;
  position: absolute;
  top: 11px;
  left: 560px;
  transition: 0.5s ease;

  /* this is just for the span*/
  font-size: 26px;
  cursor: pointer;
}

.h_1_text_box.move_up_down > .icon {
  transform: rotate(-180deg);
}

/*
.h_1_text_box:hover > .icon {
transform: rotate(-180deg);
}
*/
<div class="home_1">
  <div class="h_1_text_box">
    <h3>Our Concept</h3>
    <span class="icon">&#8645;</span>
    <!--<img class="icon" src="up_down_icon.png">-->
    <p>Text here</p>
  </div>
</div>

Comments