First of all: I am a total javascript beginner and therefore I am asking you to rate my script and tell me whether its okay or just a big mess. Note: it does work, but I guess it could be improved.
My main goal was to create a script, than can be used multiple times and does not depend on any class or id name (thats why I am using the data attribute).
$(function(){
var toggleOpen = $('*.[data-toggle="open"]');
var toggleContent = $('*.[data-toggle="content"]');
var toggleClose = $('*.[data-toggle="close"]');
var toggleSpeed = 500;
//Set height of toggle content to avoid animation jumping
toggleContent.css('height', toggleContent.height() + 'px');
//Find content to toggle
function findNextContent(target){
var nextContent = target.parent().parent().parent().find(toggleContent);
return nextContent;
}
//Toggle content
function slideToggle(target){
target.stop(true,true).slideToggle(toggleSpeed);
}
//CLose toggled content
function closeToggle(target){
target.slideUp(toggleSpeed);
}
//On Open Click
toggleOpen.click(function(){
var clicked = $(this);
var nextContent = findNextContent(clicked);
//Check if hidden to either scroll to bottom or not
if(nextContent.is(':hidden')){
slideToggle(nextContent);
smoothScrolling(toggleClose);
}else{
slideToggle(nextContent);
}
return false;
});
//On Close click
toggleClose.click(function(){
var clicked = $(this);
var nextContent = findNextContent(clicked);
closeToggle(nextContent);
return false;
});
});
What it does: It toggles an element and it also takes care of a seperate close button.
I am glad for any feedback - be it positive or negative!
"use strict"
is a feature of newer versions of JS. It means to make sure you're not doing a bunch of stuff that people accidentally do that causes lots of headaches. To use it, basically, you put that string (just that string; no var, no whatever=, none of that. just"use strict";
) as the first line of your function, and then fix all the errors you'll probably get. :) \$\endgroup\$smoothScrolling
, you can just tell the linter that it's a global, and it won't complain anymore. \$\endgroup\$