0

I'm trying to return the display value after a button is clicked, but it doesn't return the correct value.

My element: <div id="my_div" style="display: none;"></div>

After button click: <div id="my_div" style="display: block;"></div>

Javascript:

(function () {
  $('#button').trigger('click');

  return document.getElementById('my_div').style.display;
})();

Returns:

"none"

Without clicking the button (just executing document.getElementById('my_div').style.display) I get the correct output:

Executing in console:

(function () {
  return document.getElementById('my_div').style.display;
})();

Returns:

"block"

MTCoster
  • 5,868
  • 3
  • 28
  • 49
Slinidy
  • 367
  • 1
  • 4
  • 12

3 Answers3

0

Use $("#my_div).css('display') to return display value.

(function () {
  // On click
  $('#my_div').on('click', function(){
    console.log($(this).css('display'));
  });
})();
/* For testing purpose */
#my_div {
  width:100px;
  height: 100px;
  background: #999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="my_div" style="display:block"></div>
richardev
  • 976
  • 1
  • 10
  • 33
  • Return: undefined – Slinidy Feb 14 '19 at 20:47
  • @Slinidy test Snippet above does return `block` as result. Try running snippet and clicking on gray block. For testing purpose I used `console.log` to catch the value - you can change it to `return` if you like. – richardev Feb 14 '19 at 20:49
0

You can do it like this.

HTML:

<div id="my_div" style="display: none;">
</div>

<button id="button"> Click </button>

JS:

const myDiv = document.getElementById("my_div");

$("button").click(function() {
 console.log(myDiv.style.display);
 return myDiv.style.display;
});

Working pen Link

Community
  • 1
  • 1
Paolo
  • 823
  • 6
  • 18
0

That's how it worked

$("#my_button").trigger('click');
setTimeout(test, 1000);
function test() { if (document.getElementById('my_div').style.display === 'block')
    alert('test');
}

But I do not know if this is the best option

Slinidy
  • 367
  • 1
  • 4
  • 12