Discovering visible ID numbers on the screen

My content includes the following:

 <div id="sContainer">
    <div class="message0" id="l0">Initial Content 111</div>
    <div class="message1" id="l1">Initial Content 222</div>
    <div class="message2" id="l2">Initial Content 333</div>
    <div class="message3" id="l3">Initial Content 444</div>
    <div class="message4" id="l4">Initial Content 555</div>
    <div class="message5" id="l5">Initial Content 666</div>
    <div class="message6" id="l6">Initial Content 777</div>
 </div>

http://jsfiddle.net/LRLR/0sbdttds/

Additional divs are present inside the main div (not visible in this code snippet).

I am looking for a way to determine which div elements are currently visible on the screen.

Requirements: 1. Whenever a div is in focus, I need to apply a specific CSS property. 2. I also need to store a variable for each div.

Answer №1

To retrieve displayed elements, you can utilize the :visible property selector.

$(function() {
  var divs = $('[id^=l]:visible');
  console.log('displayed divs', divs);
  alert('total divs shown: ' + divs.length);
});
/* this is for testing purposes */

[id^=l] {
  /* selecting id starting with `l` */
  display: none;
}
[id^=l]:nth-child(3n) {
  /* every third element */
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sContainer">
  <div class="message0" id="l0">Initial Content 111</div>
  <div class="message1" id="l1">Initial Content 222</div>
  <div class="message2" id="l2">Initial Content 333</div>
  <div class="message3" id="l3">Initial Content 444</div>
  <div class="message4" id="l4">Initial Content 555</div>
  <div class="message5" id="l5">Initial Content 666</div>
  <div class="message6" id="l6">Initial Content 777</div>
</div>

Answer №3

If you want to determine which element is currently focused on, event delegation can help with that. Take a look at this example: http://jsfiddle.net/0sbdttds/1/

The trick is to set up a listener on the parent element, like so:

$("#sContainer").click(showMessage);

Then, within the handler function, you can use the event object to inspect the target element like this:

var focusedElement = $("#" + e.target.id);

The variable focusedElement now holds a jQuery object representing the targeted element (in this case, from a click event in the fiddle).

The provided fiddle responds to clicks, but if you need focus events, check out How to focus div?

Additionally, the CSS structure in your fiddle could be more efficient. Avoid redundancy by following best practices outlined here:

Answer №4

To identify visible elements, the :visible pseudo selector can be used to filter out the ids. I have assigned a tabIndex to make the <div>s focusable.

Take a look at the code snippet below to see it in action:

var dataXyz = '<div class="message7" tabindex="1">Focus Shifted Here</div>';
// Currently prepending just 1 <div>, but for multiple ones, use a loop to increment the tabIndex.

setTimeout(function(){  $(dataXyz).prependTo("#sContainer");},3000);

$("div:visible").each(function(){
  console.log($(this).attr('id'));
});

$(document).on("focusin", "div div", function(){
  $(this).css("background", "yellow");
});

$(document).on("focusout", "div div", function(){
  $(this).css("background", "white");
});
.message0 {margin: 30px;height: 200px;border: 10px solid green;}
.message1 {margin: 30px;height: 200px;border: 10px solid yellow;}
.message2 {margin: 30px;height: 200px;border: 10px solid pink;}
.message3 {margin: 30px;height: 200px;border: 10px solid blue;}
.message4 {margin: 30px;height: 200px;border: 10px solid black;}
.message5 {margin: 30px;height: 200px;border: 10px solid cyan;}
.message6 {margin: 30px;height: 200px;border: 10px solid orange;}
.message7 {margin: 30px;height: 200px;border: 10px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sContainer">
  <div class="message0" id="l0" tabindex="2">Initial Content 111</div>
  <div class="message1" id="l1" tabindex="3">Initial Content 222</div>
  <div class="message2" id="l2" tabindex="4">Initial Content 333</div>
  <div class="message3" id="l3" tabindex="5">Initial Content 444</div>
  <div class="message4" id="l4" tabindex="6">Initial Content 555</div>
  <div class="message5" id="l5" tabindex="7">Initial Content 666</div>
  <div class="message6" id="l6" tabindex="8">Initial Content 777</div>
</div>

Check out the updated jsFiddle here

For more details, refer to the documentation links provided below:

Answer №5

If you're looking to identify which div elements are currently in the viewport, you'll need more than just basic jQuery functionality. Consider using a specialized solution like Viewport, a custom class designed specifically for this task.

var viewport = new Viewport(window);

viewport.addEventListener("scroll:complete", function(vp) {
    viewport.querySelectorAll("div.message", function(div) {
        div.classList.add("foo");
    });
});

To simplify your code maintenance, ensure that each div you want to track in the viewport shares a common class. Keep in mind that this method is compatible with Internet Explorer 9 and newer versions, as well as other modern browsers following standard guidelines.

Answer №6

It seems like you are searching for something.

 $(document).ready(function(){
    var i,classes;
    var divs_num = $('#sContainer div').length;
     for(i = 0 ; i < divs_num; i++){
          Ids= $('#sContainer div:visible').eq(i).attr('id');
         if(typeof Ids !== 'undefined'){
             alert(Ids);
             if(Ids == 'l3' ){
                 $('#'+Ids).css('background','blue');
             }
         }
    }
    $('#sContainer div').on('click',function(){
        $('#sContainer div').css('border','5px solid blue');
        $(this).css('border','5px solid red');
    });
});

DEMO the code get all visible divs and alert all visible div Ids.. then check for example for id l3 if its visible change its background to red .. and in click event When click in any div change its border to red and change all another divs to blue border

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 Contrasts in Utilizing AJAX: A Comparative Analysis of Two

Can someone explain the distinction between utilizing AJAX in the following manner, function showHint(str) { var xmlhttp; if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE ...

utilizing Nuxt code in Elixir/Phoenix

Overview In my previous work, I combined frontend development with nuxt and backend support from elixir/phoenix, along with nginx for reverse proxy. Looking to enhance the performance of the system, my goal is now to migrate everything to Elixir/Phoenix. ...

What could be the reason for the onmessage listener not handling the initial SSE event?

When a client connects to a Node Express server, it creates a new EventSource. The server sends an SSE event upon initial connection and then at a 30-second interval thereafter. Strangely, the client's onmessage handler does not respond to the initial ...

Implementing dynamic page loading with ajax on your Wordpress website

I'm currently facing an issue with loading pages in WordPress using ajax. I am trying to implement animated page transitions by putting the page content into a div that I will animate into view. However, my current logic only works correctly about 50% ...

Styling certain UL and LI elements with CSS properties

Greetings everyone! I constantly struggle when it comes to making my CSS cooperate. I have some code that involves using ul and li tags. However, I only want to apply that styling to specific sections of my HTML code rather than all instances of the ul and ...

Guide on utilizing Subscribe Observable for performing lookup in Angular

I am new to Angular and seeking guidance as my approach may not be the best. Please advise me on a better solution if you have one. My goal is to display a list of records in table format, retrieved from the database where only Foreign Keys IDs are availa ...

Focus event in IE does not always work as expected after an ajax request is

Our current focus is on supporting IE8 exclusively. An ajax call retrieves data from the server, replaces the HTML in a container div with the response, and then attempts to focus on an element within the response. However, there seems to be inconsistenci ...

jQuery Drag Drop Sorting Feature Fails to Work when Moving Items from List to Table Cell

I need assistance with creating a sortable list that can have its items dragged into a table cell, where the items can then be sorted within that cell. The process involves: Dragging a list item into the table cell. Sorting the list item in the secon ...

Error encountered while attempting to convert CSV file: InvalidStateError

I've implemented a JavaScript function to be triggered by the 'onclick' event of an HTML button: function exportReportData2() { if ($("#Report").val() != "") { var screenParametersList = buildScreenParameters(); var ...

Is it advisable to combine ng-change with ng-blur in AngularJS?

Seeking clarification on the correct usage of AngularJS's ng-change and ng-blur from an expert. Specifically, when updating a form value. In the code snippet below, I have a dropdown where I would like to trigger overrideBusinessDec() when the user ...

A step-by-step guide on setting up an event listener for dynamically generated HTML using JavaScript objects

In my JavaScript code, I am creating object instances that include HTML elements in the form of buttons. These buttons are dynamic and have words generated dynamically as well. I want these buttons to execute certain functions when clicked. The challenge I ...

Using Django Template Variables in JavaScript Functions

Within one of my templates, there is a for loop that iterates over all the items. Whenever a user likes or dislikes an item, it should trigger a function in my code. I successfully set up the button's HTML like this: <button onclick='update_li ...

Issue encountered: Trying to deploy firebase functions and hosting with vue-cli v3 and node.js leads to an error "No npm package found in functions source directory

My plan is to utilize Vue.js for the Frontend and Firebase Functions (Express.js) + Firestore for the Backend. Step 0: I initiated a new project on Google Firebase, then created a new Service Account with Owner's permissions to be used with Admin SDK ...

Choose a specific inner div element within another div using jQuery

Trying to target a specific div within another div in my HTML structure. Here's how it looks: <div id="Stage_game_page1"><div id="cube0">[...]</div><div id="cube1">[...]</div></div> I am attempting to select #cube ...

What is the best way to prevent the click event of a container div from triggering when clicking on elements within the container using JQuery

For example: <div class="wrapper"> <div class="inner">Clicking me won't trigger the wrapper click event</div> </div> $('.wrapper').click(function(){ // Do something with the wrapper here }); However, when I cli ...

Step-by-step guide for sending data using module.exports in a node.js application

Currently, I am working on implementing a feature that will allow users to input data and store it in a database collection. The technologies I am using for this project are Node.js, MongoDB, Mongoose, Express.js, and AJAX. My goal is to capture user inpu ...

What is the reason behind one function triggering a re-render of a component while the other does not in Next.js?

I am currently working on a Next.js web application where one of the pages contains two functions that utilize useState() to add or remove emails from an array. const [invites, setInvites] = useState([]) // other code const lmao = () => { console.lo ...

Files on video input are now accepting audio attribute

Currently, I am adding a file upload feature to my application. I have created input fields for various types of media. <label>Images<input type="file" accept="image/*"/></label> <label>Videos<input type="file" accept="video/*"/ ...

The click functionality appears to be malfunctioning

I encountered an issue with my code related to the click events. The problem is that one click event doesn't work after another one. Here is my ajax and jquery code: <!-- Placeholder for confirmation modal when gevonden button is clicked, then u ...

The HTML elements may have identical heights, but visually, one appears larger than the other

The size of the "login to enter chat" button seems to be larger than the messageBox div, despite adjusting padding and margins. What could be causing this issue? Any suggestions on how to fix this design glitch? #chatbox { width: 500px; height: ...