PapaBless PapaBless - 20 days ago 8
CSS Question

Simplify multiple function for each IDs

I created a simple code that slides-in and out the toggled image using JQuery and CSS. I used multiple functions to hide/toggle the others when you click another image. Is there a way to minimize the usage of this?. Plus, when I click a different image for a third time, I have to double-click before it slides back. My code.. and its JSFiddle

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("#img1").toggle(
function () {
$("#img1").css({"transform": "translate3d(-100px, 0px, 0px)"});
$("#img2").css({"transform": "translate3d(0px, 0px, 0px)"});
$("#img3").css({"transform": "translate3d(0px, 0px, 0px)"});
},
function () {
$("#img1").css({"transform": "translate3d(0px, 0px, 0px)"});
}
);
$("#img2").toggle(
function () {
$("#img2").css({"transform": "translate3d(-100px, 0px, 0px)"});
$("#img1").css({"transform": "translate3d(0px, 0px, 0px)"});
$("#img3").css({"transform": "translate3d(0px, 0px, 0px)"});
},
function () {
$("#img2").css({"transform": "translate3d(0px, 0px, 0px)"});
}
);
$("#img3").toggle(
function () {
$("#img3").css({"transform": "translate3d(-100px, 0px, 0px)"});
$("#img2").css({"transform": "translate3d(0px, 0px, 0px)"});
$("#img1").css({"transform": "translate3d(0px, 0px, 0px)"});
},
function () {
$("#img3").css({"transform": "translate3d(0px, 0px, 0px)"});
}
);
});
</script>
</head>
<title></title>
<style>
.cardcont img {
transition: transform .2s ease-in-out;
}
.cardcont #img1 {
position:absolute;
left:0;
top:0;
z-index:-1;
}
.cardcont #img2 {
position:absolute;
left:200px;
top:0;
z-index:-1;
}
.cardcont #img3 {
position:absolute;
left:400px;
top:0;
z-index:-1;
}
</style>
</head>
<body>
<div class="cardcont">
<img src="http://i65.tinypic.com/fokk9j.jpg" id="img1"/>
<img src="http://i65.tinypic.com/fokk9j.jpg" id="img2"/>
<img src="http://i65.tinypic.com/fokk9j.jpg" id="img3"/>
</div>

</body>
</html>

Answer

Here's a shorty using this and :not..

css (added)

.cardcont img {
  transform: translate3d(0px, 0px, 0px);
  transition: transform .2s ease-in-out;
}

.active-image {
  transform: translate3d(-100px, 0px, 0px)!important;
}

jquery

$(function() {
  $('img').click(function() {
    $('img').not(this).removeClass('active-image');
    $(this).toggleClass('active-image');
  });
});

fiddle

https://jsfiddle.net/Hastig/98dxLy5c/

Comments