Adding and removing classes of different elements
So, I'm currently learning jquery and a little tweenlite for animation (I want to keep it as my main one). So im currently creating a portfolio grid, but I want to add on click of an item that the other item fades out (sliding from the right it doesn't matter).
But I can't find a way to make it work so that 1 item has 1 window to show and another item has another window to show without repeating the code over and over and changing the simple number every time, there must be a way to make it work without repeating the code over and over.
I created a code to show where my struggle is.
I hope I have described this problem clearly enough :)
Html
<div class="box">
<div class="show">Show 1</div>
</div>
<div class="bigbox">
<div class="removeit">
<div class="bigshow">Bigshow 1</div>
</div>
</div>
<div class="box">
<div class="show">Show 2</div>
</div>
<div class="bigbox">
<div class="removeit">
<div class="bigshow">Bigshow 2</div>
</div>
</div>
</div>
CSS
.container {
overflow: auto;
margin: 0 auto;
width:500px;
}
.box {
height:200px;
width:200px;
background:yellow;
text-align:center;
cursor:pointer;
margin:0 auto;
float:left;
margin-right:50px;
}
.bigbox {
height:100%;
width:100%;
background-color: grey;
z-index:100;
left:0;
opacity: 0;
position: fixed;
display:none;
top:0;
.removeit {
height:100px;
width: 100px;
top: 0;
right:0;
background-color: blue;
margin:0 auto;
cursor:pointer;
}
}
.show {
display:block;
}
.noscroll {
overflow:hidden;
}
Javascript
$(".box").click(function(){
$(".bigbox").addClass("show");
TweenLite.to($('.bigbox'), 0.5, {
opacity:1,
autoAlpha:1
});
});
$(".removeit").click(function(){
TweenLite.to($('.bigbox'), 0.5, {
autoAlpha:0,
opacity:0
});
});
Codepen
source to share
As I mentioned in the comments, I think this is possible if we find a common language between box and bigbox , and if we do not change the HTML. This common stem should be the index value from their respective classes.
- So, first save the variable clickedIndex, clicks inside the handler for example
var clickedIndex=$('.box').index($(this));
. - And then post the clickedIndex, to obtain selective BigBox , for example
var bigbox=$(".bigbox").eq(clickedIndex);
. - Finally, use this bigbox variable to fade in or out.
Here's your modified JavaScript:
var bigbox = null;
var clickedIndex = -1;
var boxElements=$(".box");
var bigboxElements=$(".bigbox");
var removeItElements=$(".removeit");
boxElements.click(function() {
clickedIndex = boxElements.index($(this));
bigbox = bigboxElements.eq(clickedIndex);
bigbox.addClass("show");
TweenLite.to(bigbox, 0.5, {opacity: 1,autoAlpha: 1});
});
removeItElements.click(function() {
clickedIndex = removeItElements.index($(this));
bigbox = bigboxElements.eq(clickedIndex);
TweenLite.to(bigbox, 0.5, {autoAlpha: 0,opacity: 0});
});
The only problem with this approach is that it is highly dependent on the order in which the HTML was laid out.
source to share