What is the element known as the "solely-visible-offspring"?

I am dealing with a large outer div that contains several identical circles (each being a smaller div with border-radius set to 100%).

Using jQuery, I have implemented a function to fade out these circles when a user clicks on them. However, I want to trigger an additional event when the only remaining circle is clicked.

:last-child or :nth-child() selectors won't work in this case because it doesn't matter which circle is clicked until there is only one left.


It's important to note that even though the elements are FADED OUT, they remain as siblings of the visible elements. Therefore, I need to select the "last visible" element.

<div>

<div class="circle"></div>

<div class="circle"></div>

<div class="circle"></div>

<div class="circle"></div>

<div class="circle"></div>

<div class="circle"></div>

<div class="circle"></div>

<div class="circle"></div>

</div>

$(document).ready(function(){
    $(".circle").click(function(){
        $(this).fadeOut("slow");
    });
    $("XXX").click(function(){
        alert("I was the last of Mohicans");
    });
});

Answer №1

What if we try this instead?

.circle:first-child:last-child {

Maybe it will work better.

UPDATE based on revised question :

If you are looking to check if the element is the only one visible after clicking, you could implement the following logic:

$(document).ready(function(){
    $(".circle").click(function(){
        $(this).fadeOut("slow");
        if ($('.circle:visible').length>1) return; // exits if not the last one
        alert("I was the last of Mohicans");
    });
});

Answer №2

Have you heard about jQuery's only-child selector? Check it out here: http://api.jquery.com/only-child-selector/

(I hope I've understood your question correctly)

Based on the recent edits to the question, here is a revised suggestion:

You could try implementing something like this:

$(document).ready(function(){
    $(".circle").click(function(){
        var numCircles = $('.circle').length;
        var numFaded = $('.faded').length;
        if( (numCircles - numFaded) == 1 ) {
            alert("I was the last of Mohicans!");
        }
        $(this).fadeOut("slow");
        $(this).addClass("faded");
    });
});

I admit that my solution may not be the most efficient (I'm no expert in JavaScript/jQuery), but it should work fairly quickly (unless you add a huge number of circles) and meet your requirements.

Keep in mind that I haven't tested the code above. If it doesn't work, hopefully it can still point you in the right direction. Feel free to leave a comment below if you need further assistance.

Answer №3

To overcome this issue, consider adding an additional class to the specified divs and targeting them using `:only-child` selector. Upon clicking on $(".extraclass :only-child"), you can then add your desired event. Otherwise, remove the extra class and implement a fade-out effect.

Answer №4

$(document).ready(function () {
  $(".circle").click(function () {
   var $this = $(this);
   $this.fadeOut("slow");
   if ($this.siblings(':visible').length === 0) {
     alert("I was the last of Mohicans");
   }
 });
});

It is recommended to consider the count of visible siblings when working with this function... If necessary, a class selector can also be added for specificity.

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

How to create multi-colored vAxis ticks in Google Charts with corresponding light backgrounds

I have been working on customizing the vAxis ticks in my Google chart to display multiple colors. Here is the code I currently have: var gridlines = [ '#ff0000', '#00ff00', '#0000ff' ]; var container = document.get ...

What is the best way to narrow down a selection of elements in d3js?

I am trying to implement a feature where all elements below the one that is being hovered over will translate downwards. Currently, I am able to filter the selection using .filter for elements greater than 10. Is there a way to dynamically use the id of th ...

The vertical alignment of the wrapper div does not support multiple lines of text

I am having trouble achieving vertical alignment (middle) for a div with 2 lines of text. I can do it with one line, but not two. I want one of the lines to be formatted like a h2 heading, and the other like a regular paragraph. I understand that I could s ...

Determine the number of children within the parent container and delete one child at a time by clicking on the button until all children are removed

My challenge lies in deleting all child divs except the last one in each parent div with the same class. Below is my code structure along with my JavaScript function to remove a child div called repeating-div: $('.repeatable').on('click&a ...

The script fails to load under the specified circumstances

Is there a way to load a script only after the user has logged in to the app and when a specific page is finally made visible? I've tried setting the page to display block using an AJAX call, but even after doing so, the script doesn't load as ex ...

Exclude items from AngularJS watch list

Is there a way to manually run a digest loop on specifically selected watches? Take, for example, the scenario where I need a directive that constantly displays the current time (including seconds), but without triggering the digest loop every second. One ...

Fetching JSON data with CodeIgniter

Struggling to fetch JSON data from my PHP file. It's been quite challenging. Here is the code snippet: The code in my VIEW: var productDetails = {'id':ISBNNumber,'qty':finalqty,'price':finalprice,'name':bookTi ...

Animating range tick movements as the range thumb moves

My custom range input includes a span that displays the range's value and a div with multiple p elements acting as ticks. To create these ticks, I had to use a custom div because using "appearance: none" on the range hides the ticks by default. The ti ...

Hiding the date picker in Bootstrap once a date has been chosen

Currently, I am utilizing the Bootstrap date picker in my project. My goal is to hide the date picker dialog box once a user selects a date. Here is the code snippet that represents my effort: var from_close = $(document).on('focus', ".date-p ...

Ways to deselect checkboxes and eliminate validation requirements

Below is the HTML code snippet that I am working with: <div class="form-group"> <div class="input-group"> <label for="daterange-vacancy" class="input-group-addon">Van</label> ...

DOM is set for Jquery activation

I'm dealing with an issue in JQuery that I recently started working on. I have a large HTML page with a widget at the beginning, but when I use document.ready, it waits for the entire page to load before executing, which takes too long. Is there a wa ...

Customizing mediaquery styling in Bootstrap

Below is the example code showcasing #data in either md-12 or sm-6 depending on browser width. Under certain conditions (such as a special preview mode triggered by JavaScript), I wish to override the rendering rules for #data and display only in col-md-12 ...

When using :hover in CSS, it overrides any other styles applied to the parent container

In my recent exploration on this particular pen, I encountered an issue with the hover effect of a link causing the styles of its containing div to disappear. Interestingly, this problem is resolved when I adjust the CSS from #div div {background-color:b ...

Displaying only 10 rows out of a total of 1000 with Datatable's deferloading

My API retrieves 1000 accounts, but I only want to display the first 10 and load more when the user clicks on "next." HTML table <table id="example" class="display" cellspacing="0" width="100%"> <thead ...

Replacing a <button> element with an <a> tag while preserving all attributes

<div class="pagination"> <button class="ajax left" data-href="" rel="prev"></button> <button class="active">1</button><button class="ajax" data-href="/legenda/carrega_destaques/todos/2">2</button> ...

Discover the CSS styles that Bootstrap has implemented on this element

My footer and logo look great without bootstrap, but when I add it in, everything gets messed up. I'm not sure what styles bootstrap is applying to the elements, making it difficult to troubleshoot. I know I can override the styles, but I need to firs ...

Prevent jquery-ui datepicker from opening when the confirmation box is cancelled

Here are the snippets of code I'm currently working with: HTML, Date : <input id="datepicker"> Fare : <input id="fare"> JS, <script> $(function(){ $("#datepicker" ).datepicker({ changeMonth: true, ...

Modify the CSS of the gauge element without causing any issues

I am facing an issue while trying to resize this gauge element. Whenever I attempt to modify the container class to make it smaller, the entire gauge ends up distorting. Changing the position to relative seems to cause glitches at the edge of the gauge. An ...

Display a Div Element Upon Clicking Checkbox or Radio Button

Looking for a way to display Divs related to checkbox radio buttons in the title. After attempting to implement scripts from past discussions, I still feel like something is missing. The goal is simple - clicking on the Second button (checkbox radio tool ...

Tips for retrieving information from a controller using AJAX technology?

I am currently using Laravel and have set up a controller to retrieve data from an external API. I have successfully fetched the data and displayed it in a select drop-down menu. Due to the size of the data, I would like to only fetch this result when a u ...