Using a function on a singular element

I'm currently working on my portfolio and I would like to organize my projects in a menu similar to this felipestoker.com

When you click on Works, it displays a menu with my projects categorized. However, when I click on a category, all of them appear. Refer to this image:

Here is the outcome:

How can I resolve this issue?

A snippet of my code:

$(".worksList h2").click(function() {
  $(".worksList ul").slideDown();
  $(".worksList i").removeClass("fa-plus-square-o");
  $(".worksList i").addClass("fa-minus-square-o");
});
#works {
  width: 300px;
  height: 100%;
  background: #474747;
  position: fixed;
  right: 0;
  top: 0;
  ;
  *display: none;
  */ z-index: 3;
  padding: 20px;
  box-sizing: border-box;
}
#works span {
  font: 700 23px/23px"Open Sans";
  text-transform: uppercase;
  color: white;
  text-align: left;
  display: inline-block;
}
.worksList h2 {
  font: 300 15px/30px"Open Sans";
  color: #d9cfcf;
  text-transform: uppercase;
  text-align: left;
}
.worksList h2:hover {
  color: white;
}
.worksList h3 {
  font: 700 15px/30px"Open Sans";
  color: #fff;
  text-transform: uppercase;
}
.float-left {
  float: left;
}
.float-right {
  float: right;
}
.float-none {
  float: none;
}
.display-block {
  display: block
}
.display-inline-block {
  display: inline-block;
}
.display-table-cell {
  display: table-cell;
}
.display-none {
  display: none;
}
/*BACKGROUND*/

.background-white {
  background: #fff
}
.background-gray47 {
  background: #474747
}
<div id="works"><span class="worksClose cursor-pointer">X   Fechar</span>
  <span class="bar background-white margin-top-30 margin-bottom-30"></span>

  <div class="worksList">
    <!-- Series -->
    <h2 class="text-align-center cursor-pointer">
<i class="fa fa-plus-square-o"></i>
Series
</h2>
    <ul class="display-none">
      <li class="display-block grid_100p margin-top-10">
        <a class="display-inline-block" href="http://www.lilyhammer.com.br">
          <img class="float-left" src="./images/1.png" alt="Lilyhammer" title="Lilyhammer" width="30" height="30" />
          <h3 class="float-left margin-left-15">Lilyhammer</h3>
        </a>

      </li>
      <li class="display-block grid_100p margin-top-10">
        <a class="display-inline-block" href="http://www.punhodeferro.com.br">
          <img class="float-left" src="./images/1.png" alt="Punho de Ferro" title="Punho de Ferro" width="30" height="30" />
          <h3 class="float-left margin-left-15">Punho de Ferro</h3>
        </a>

      </li>
      <li class="display-block grid_100p margin-top-10">
        <a class="display-inline-block" href="http://www.westworld.com.br">
          <img class="float-left" src="./images/1.png" alt="West World" title="West World" width="30" height="30" />
          <h3 class="float-left margin-left-15">West World</h3>
        </a>
      </li>
    </ul>
    <!-- Special Mention -->
    <h2 class="text-align-center cursor-pointer">
<i class="fa fa-plus-square-o"></i>
Special Mention
</h2>
    <ul class="display-none">
      <li class="display-block grid_100p margin-top-10">
        <a class="display-inline-block" href="http://www.pulpfiction.com.br">
          <img class="float-left" src="./images/pulp.png" alt="Pulp Fiction Brasil" title="Pulp Fiction Brasil" width="30" height="30" />
          <h3 class="float-left margin-left-15">Pulp Fiction Brasil</h3>
        </a>

      </li>
    </ul>
  </div>
</div>

Answer №1

To effectively target the desired clicked element, you can utilize .each() and .eq() as shown below:

$(".worksList h2").each(function (i) {
    $(this).click(function () {
        $(".worksList ul").slideUp().eq(i).slideDown();
        $(".worksList").find("i").removeClass("fa-plus-square-o").eq(i).addClass("fa-minus-square-o");
    });
});

Important: The addition of .slideUp() ensures that previously expanded elements will close when a new one is selected. Some refinement may be necessary


UPDATE: The updated code allows for toggling the lists with each click

jQuery(document).ready(function ($) {
    $(".worksList h2").each(function (i) {
        $(this).click(function (e) {
            e.preventDefault();
            var _this = $(this);
            var _parent = _this.parent(".worksList");
            var _sibling = _this.next("ul");
            if (_sibling.hasClass("expanded")) {
                _sibling.slideUp(function () {
                    _parent.find("i").addClass("fa-plus-square-o").removeClass("fa-minus-square-o");
                }).removeClass("expanded");
            } else {
                $(".worksList").find("ul").slideUp(function () {
                    $(".worksList").find("i").removeClass("fa-minus-square-o").addClass("fa-plus-square-o");
                }).removeClass("expanded").eq(i).slideDown(function () {
                    _parent.find("i").eq(i).removeClass("fa-plus-square-o").addClass("fa-minus-square-o");
                }).addClass("expanded");
            }
        })
    });
}); // ready

Answer №2

Give this snippet a shot

$(".clickableList").on("click", function() {
  $(this).find("header ul").slideDown();
  $(this).find("header i").removeClass("icon-plus").addClass("icon-minus");
});

Answer №3

It appears that currently,

$(".worksList h2").click(function() {
  $(".worksList ul").slideDown();
  $(".worksList i").removeClass("fa-plus-square-o");
  $(".worksList i").addClass("fa-minus-square-o");
});

The code above is targeting all ul elements in the .worksList. This is causing all lists to expand. To make the event more specific, it should be tied to the particular element, and then target the next ul based on the code.

For example:

$(".worksList h2").click(function() {
  $(this).next("ul").slideDown();
  ...
});

To make it specific to each h2 heading, you must specify each heading individually. Thus, encapsulate the function like this:

jQuery(document).ready(function ($) {
    $(".menu-title").each(function(i) {
        $(this).click(function (e) {
            e.preventDefault();
            $(this).next("ul").slideDown();
        });
    });
});

At some point, sliding up the menu might be necessary as well.

A faster alternative could be using slideToggle like this:

jQuery(document).ready(function ($) {
    $(".menu-title").each(function() {
        $(this).click(function (e) {
            e.preventDefault();
               $(this).next("ul").slideToggle();
        });
    });
});

Logic should be implemented to add/remove different classes to the i icon. The following code checks if the clicked menu h2 has a fa-plus-square-o class icon and adjusts it accordingly.

if ($(this).find("i").hasClass("fa-plus-square-o")) {
               $(this).find("i").removeClass("fa-plus-square-o").addClass("fa-minus-square-o");
               } else {
                   $(this).find("i").removeClass("fa-minus-square-o").addClass("fa-plus-square-o");
               }

Combining all the code:

jQuery(document).ready(function ($) {
    $(".menu-title").each(function() {
        $(this).click(function (e) {
            e.preventDefault();
            $(this).next("ul").slideToggle();
            if ($(this).find("i").hasClass("fa-plus-square-o")) {
              $(this).find("i").removeClass("fa-plus-square-o").addClass("fa-minus-square-o");
            } else {
               $(this).find("i").removeClass("fa-minus-square-o").addClass("fa-plus-square-o");
               }
        });
    });
});

For a demo, visit the jsFiddle link: http://jsfiddle.net/63n4wyov/2/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the potential of Framework7 in Single Page Applications: optimizing performance by preloading

I'm currently working on developing a web application using Framework7. Framework7 offers routing APIs for navigating between HTML pages. It seems that the pages are loaded dynamically through AJAX requests. I am curious if it is possible to preload ...

Unable to adjust font for headings using CSS and Bootstrap

Looking to expand my skills in HTML and CSS, I've encountered a bit of a hiccup. Utilizing Bootstrap for my webpage, here's the simplified version of what I have so far: index.html: <!DOCTYPE html> <html> <head> <lin ...

Personalizing the Twitter Embedded Timeline

I am curious about how much customization options are available for the Embedded Timeline. I searched through the documentation but still have some unanswered questions - maybe I missed something. My goal is to initially display only one tweet and then ha ...

Tips for retrieving a variable from a $.getJSON function

My question is similar to this one: How can I return a variable from a $.getJSON function I have come across several duplicates on Stack Overflow, but none of them provided a satisfactory answer. I understand that $.getJSON runs asynchronously, and I hav ...

Angular's scope allows for the application of CSS classes exclusively to the first div element

Every 2 seconds, a JavaScript function is being called that updates a specific div on the view when a certain condition is met. <div id="ball_{{ballIndex}}">{{ball}}</div> This is controlled by the ng controller. var myCounter = 0; ...

A guide on developing a Website Tour using jQuery

Exploring ways to create a website tour for first-time users? I've been searching for free website tour plugins and came across this one: http://tympanus.net/codrops/2010/12/21/website-tour/ However, the instructions provided are quite brief, making ...

Dynamic table sorting with JQuery using ajax for automatic updating of the table's header and body sections

I am currently working on integrating table sorting into a Rally app using dojo and the jquery tablesorter plugin. I am facing difficulty in setting up the update callback for the tablesorter. My HTML structure includes: <table id='myTable' ...

Trigger a popup notification with JavaScript when

Check out this snippet of code: <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/ ...

Errors in AJAX calls can sometimes result in an "ERR_EMPTY_RESPONSE" being

I'm currently working on a small CMS/Social network project for a school, which is quite complex and heavily relies on AJAX technology. Randomly, I encounter issues where calls are blocked and the browser displays an error message like net :: ERR_EMPT ...

Why must I handle Access-Control-Allow-Origin issues with XMLHttpRequest() but not with forms?

When attempting to make a request using XMLHttpRequest(), I encounter the Access-Control-Allow-Origin error. However, when I use a form like the one below, no issues arise. Is there something about forms that allows access? What could be the reason for t ...

What is the best way to load all elements on a webpage while utilizing an HTML parser?

Looking to compile a full list of available items for purchase on a specific website can be quite challenging. The webpage in question seems to only display 12 items at a time, and requires manual scrolling to load more. Is there a way, perhaps through C# ...

Modify the class of an input while typing using Jquery

Recently, I created a form using Bootstrap 4. The validation process is done through a PHP file with an AJAX call and it's functioning correctly, except for one issue. I want the input class to switch from "invalid" to "valid" as soon as the user begi ...

Gradient transition effect changing background color from bottom to top

I am facing an issue where I have a block and I want the background color to animate from bottom to top on hover. Can you please help me identify what is causing this problem? Your assistance is greatly appreciated. .right-block--wrapper { backgroun ...

What could be causing the tabs to disappear from the Material UI tab component in my React project?

What am I currently working on? I am in the process of developing a horizontally scrollable tab component to select dates within a month For this project, I have decided to utilize the Material UI library Issues Encountered The dates before the 14th Sun ...

"Enjoy a full-screen background that adjusts its height while you scroll

Here is how my HTML elements are nested: body { app-root { app-block-page { app-block-content { div.wrapper { *content* } } } } } body has width:100% and ...

What is the best way to ensure the content div fills all available space? (JQM compatibility concerns)

Currently, I am facing an issue with displaying a pdf in an iFrame within my app. The problem lies in the fact that the iFrame does not occupy the entire space between the header and footer divs on the page. I am utilizing Jquery Mobile 1.1.0 for the theme ...

Separating a picture into distinct sections

Is there a way to divide an image into different parts to create hover effects? For example, hovering over the top part of the image triggers one change, and hovering over the bottom part triggers another change. This example demonstrates this concept usin ...

Add Text to Bootstrap Modal Window

The bootstrap modal body is not containing all of my content and some of it is overflowing. <div class="modal fade" tabindex="-1" role="dialog" id= "blockModel"> <div class="modal-dialog"> <div class="modal-content"> < ...

What is the maximum number of files that FileUploader can accept when multi-select is enabled?

I encountered the following issue: A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll Additional information: Maximum request length exceeded. while attempting to upload 250 JPEG files, each around 98 KB in ...

Making a CSS table fit perfectly inside a container

After reading numerous recommendations on the subject, none of them seem to be effective in my particular situation. The issue lies with a table that is nested within a container ('div' element) as shown below: <div class="container"> ...