1

I have a php function:

function myfunc() {

//then I have a div...

echo '<div class="overlay">';
echo "<button onclick=\"$('.overlay').hide();\">Close</button>";
echo '</div>';

}

My problem is that when I click on the close button the div is not hiding.

What I'm I doing wrong here?

4
  • Any error message in the JavaScript console? Commented Oct 18, 2012 at 9:40
  • No, I can see no errors in the js console Commented Oct 18, 2012 at 9:42
  • your code is working correctly no problem in that check one again Commented Oct 18, 2012 at 9:44
  • You may need to escape the $, since it's inside a double-quoted string. Commented Oct 18, 2012 at 9:51

4 Answers 4

5

Avoid to hardcode javascript handlers and inline events inside the output of php code: do instead

echo '<div class="overlay">';
echo "<button>Close</button>";
echo '</div>';

and previously insert in your page this code that detects a click on your button using event delegation

<script>
  $(document).on('click', '.overlay button', function() {
      $(this).parent().hide()
  });
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

button is child of overlay. Why event delegation?
Sorry, misread the markup. Updated. I've used event delegation because AFAIK that could be the response of an ajax call (so the code could be injected later on DOM) and, as a general rule, if you have many elements to handle, this approach is better than attaching an handler on each element
I tried the code above but it's just hiding the iside content of the div and the button but not the actual div
2

try:

<button onclick="this.parentNode.style.display = 'none'; return false;">Close</button>

3 Comments

Tried: echo '<button onclick=\"this.style.display = 'none'; return false;">Close</button>'; but the page goes blank so there's a syntax issues here?
Since that's a single-quoted string, you need to escape single quotes, not double quotes, inside it.
Sorry, a bit irresponsible that I just posted without testing x| This one works now. It hides the parentNode which is the div.
2

Try this code:

function myfunc() {

//then I have a div...

echo '<div class="overlay"  id="overlay" >';
echo "<button onclick=\"hide()\">Close</button>";
echo '</div>';

}
//using the javascript code:
function hide()
{
    document.getElementById("overlay").style.display="none";

}

1 Comment

Tried it but it didn't hide the div
0

try:

$('.overlay button').live('click',function(
    $('.overlay').css({'display': 'none'});
));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.