I\'m new to javascript, I\'m wondering how to get .contact from a 30% width to 40% when I go with my mouse over .contact. This works, but while .contact gets bigger I want .
You can do it with Flexbox
flex: 1
makes .contact
expand to the rest of the available space.
You would then only need to define the width for .div
and its width when .contact
is hovered.
.content {
display: flex;
}
.contact{
background-color:red;
flex: 1
}
.div {
width: 70%;
background-color: blue;
}
.contact:hover + .div {
width: 60%
}
<div class="content">
<div class="contact" id="contact">
<h3> Text</h3>
<p>More textt</p>
</div>
<div class="div">
<h3> Text</h3>
<p>More textt</p>
</div>
</div>
You can do this with only CSS
.contact {
background-color: red;
width: 30%;
float: left;
transition:1s linear;
}
.div {
background-color: blue;
width: 70%;
float: right;
transition:1s linear;
}
.contact:hover {
width: 40%;
}
.contact:hover + .div{
width: 60%;
}
<div class="content">
<div class="contact" id="contact">
<h3> Text</h3>
<p>More textt</p>
</div>
<div class="div">
<h3> Text</h3>
<p>More textt</p>
</div>
</div>
And for a more flexible way you can consider flexbox where you only need to change the hover element and the other one will shrink by default
.content {
display: flex;
}
.contact {
background-color: red;
flex-basis: 30%;
transition: 0.5s linear;
}
.div {
background-color: blue;
flex-grow:1;
}
.contact:hover {
flex-basis: 40%;
}
<div class="content">
<div class="contact" id="contact">
<h3> Text</h3>
<p>More textt</p>
</div>
<div class="div">
<h3> Text</h3>
<p>More textt</p>
</div>
</div>
UPDATE
If you want a permanent change you can try animation:
.content {
display: flex;
}
.contact {
background-color: red;
flex-basis: 30%;
transition: 0.5s linear;
animation:big 0.5s linear forwards;
animation-play-state:paused;
}
.div {
background-color: blue;
flex-grow:1;
}
.contact:hover {
animation-play-state:running;
}
@keyframes big{
to {flex-basis: 40%;}
}
<div class="content">
<div class="contact" id="contact">
<h3> Text</h3>
<p>More textt</p>
</div>
<div class="div">
<h3> Text</h3>
<p>More textt</p>
</div>
</div>
You don't need javascript for this, sibling selector works.
Or in javascript, shrink the div on the right while expanding the div on the left.
var width = 30;
var maxWidth = 40;
var interval = null;
var contact = document.getElementById("contact");
var div = document.getElementById("div");
function myMove() {
interval = setInterval(function() {
if (width>= maxWidth){
return clearInterval(interval);
}
contact.style.width = ++width + "%";
div.style.width = (100-width) + "%";
},5);
}
.contact{
background-color:red;
width:30%;
float:left;
}
.div{
background-color: blue;
width: 70%;
float: right;
}
<div class="content">
<div class="contact" id="contact" onmouseover="myMove()">
<h3> Text</h3>
<p>More textt</p>
</div>
<div class="div" id="div">
<h3> Text</h3>
<p>More textt</p>
</div>
</div>