I am currently using jQuery to identify which IDs have a specific class name. This information is crucial as I am employing toggleClass() from jQuery to display and hide certain divs. When a button is selected, I want a viewport to either appear or disappear. My objectives include mastering this technique in jQuery and gaining an understanding of how it can be done in pure JavaScript. I am aware that the JavaScript approach will be more complex, but I am ready for the challenge.
- How can I utilize the resetViewport() function to count the number of "selected" classes?
- Is there a more efficient method to achieve this task?
- In JavaScript, how can one accomplish the same functionality? Feel free to suggest specific methods in JS without providing exact code. My primary goal is to learn.
To provide clarity, I have included the code snippet. Let's begin by examining my personal website hosted at CodeAmend along with the associated code:
****html***
<!DOCTYPE html>
<html lang="en">
... (omitted portion of HTML content)
</html>
* Here is the JavaScript / jQuery *
$("[id^=button]").click(function () {
$(this).toggleClass('selected');
// Creates the ID of a viewport: "view-" + inner HTML of button
var viewID = "#view-" + $(this).html();
$(viewID).toggle();
resetViewport(4);
});
function resetViewport(numberOfViewports) {
var viewSize;
switch (numberOfViewports) {
case 1:
viewSize = "400px";
break;
case 2:
viewSize = "198px";
break;
case 3:
viewSize = "131px";
break;
case 4:
viewSize = "98px";
break;
}
$("[id^=view]").css("width", viewSize);
}
Here is the CSS
* {
margin: 0;
padding: 0;
}
... (omitted portion of CSS content)