97

I'm using JS as a way of changing the content of an SPA I'm creating. When I press a button to change the content the HTML changes from this:

<div id="selectDiv" style="display: none;">

to this:

<div id="selectDiv" style>

Now part of my SPA has a div that contains a number of checkboxes, each representing a div, and so when I press the submit button, the next div that should be displayed will be the first item in the checkbox list that was selected.

I'm wondering if there's a way in JQuery for the code to "almost detect" which div is now visible. something like this:

if($('#selectDiv').isVisible()){
    //JS code associated with this div.
}

Any suggestions?

4
  • Could you not mess around with the .hasClass function to do something like this? Check if an element has a certain class and then go from there? Commented Nov 7, 2016 at 15:40
  • if(document.getElementById("selectDiv").style.display !== "none"){...} Commented Nov 7, 2016 at 15:41
  • What do you mean by "almost detect"? You could use $elem.is(":visible") to determine is the element is visible! Commented Nov 7, 2016 at 15:42
  • check this one - stackoverflow.com/a/72112111/14229690 Commented May 4, 2022 at 11:38

1 Answer 1

146

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

console.log($('#selectDiv').is(':visible'));
console.log($('#visibleDiv').is(':visible'));
#selectDiv {
  display: none;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectDiv"></div>
<div id="visibleDiv"></div>

Sign up to request clarification or add additional context in comments.

8 Comments

Hey there - not disputing the correctness of this answer, but please consider suggesting or voting on a dupe for questions like these. There are already some pretty comprehensive answers that exist on Stack Overflow that we can point this question to instead.
Could I do something like this? $(document).ready(function () { if ($('#selectDiv').is(':visible')) { //JS code associated with this div. } });
Yes, see my update.
@JacksonSentzke any thoughts?
It runs in the code snippet, but it's not running in my code. It's now just trial and error to get it working.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.