Home › Forums › JavaScript › Cleaner way of writing this code?
- This topic is empty.
-
AuthorPosts
-
May 2, 2013 at 12:25 am #44496
Rugg
ParticipantHi,
I’m curious if anyone can suggest a cleaner, more efficient method for writing the following jQuery. The code seems to be redundant in certain places…Any help or suggestions are appreciated. Thank You!
$(‘#one’).click(function () {
$(‘.two’).fadeTo(400, 0.5);
$(‘.one’).fadeTo(400, 1);
return false;
});$(‘#two’).click(function () {
$(‘.one’).fadeTo(400, 0.5);
$(‘.two’).fadeTo(400, 1);
return false;
});$(‘#all’).click(function () {
$(‘.one, .two’).fadeTo(400, 1);
return false;
});May 2, 2013 at 1:26 am #133811Alen
ParticipantMay 2, 2013 at 1:40 am #133813TheDoc
MemberI’m not sure I really like this solution, but it’s a lot more flexible in terms of adding more and more items.
http://codepen.io/ggilmore/pen/c2ff9d85937f4f62cf1bbf6024552321
May 2, 2013 at 5:22 pm #133906TheDoc
MemberMy method is definitely a better way to go, I think.
Here it is with your markup: http://codepen.io/ggilmore/pen/db239cfbc984feab0c4679abddf51841
May 2, 2013 at 5:29 pm #133910TheDoc
MemberIt’s fancy shmancy SCSS.
Example using CSS:
.something {
/* styles */
}.something.active {
/* different styles */
}SCSS:
.something {
/* styles */&.something {
/* different styles */
}
}May 2, 2013 at 5:37 pm #133914TheDoc
MemberSure, if you want to think of it that way. `&` simply means: Use the parent selector and tack this on *directly* to it. Emphasis added because there’s a big difference if you don’t include the `&`.
Example A:
.something {
/* styles */.active {
/* different styles */
}
}Example B:
.something {
/* styles */&.active {
/* different styles */
}
}Example A will render:
.something {
/* styles */
}.something .active { /* note the _space_ between .something and .active */
/* different styles */
}Example B will render:
.something {
/* styles */
}.something.active { /* no _space_ between .something and .active */
/* different styles */
}May 2, 2013 at 5:46 pm #133916TheDoc
MemberUpdated it: http://codepen.io/ggilmore/pen/db239cfbc984feab0c4679abddf51841
Just need to add the active class to each of the boxes and the ‘All’ nav item.
May 2, 2013 at 5:50 pm #133919CrocoDillon
Participant> Just need to add the active class to each of the boxes and the ‘All’ nav item.
That’s probably a better way to do it but it’s easier to just add `$(‘.nav .all’).click();` after the click listener.
May 2, 2013 at 6:20 pm #133927TheDoc
Member@CrocoDillon, I thought about that, actually. At the end of the day, if I can do it without JS, that’s my choice.
May 3, 2013 at 1:54 pm #133981Merri
Participant -
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.