Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close a window with JavaScript onClick

On my website I have 4 Windows (identified by target1, target2, target3 and target4). On these Windows I want to add a button with a name of "close" and using an onClick event call the correct function depending on which window.

function close_window1(){
    document.getElementById('target1').style.display = 'none';  
}

function close_window2(){
    document.getElementById('target2').style.display = 'none';  
}

function close_window3(){
    document.getElementById('target3').style.display = 'none';  
}

function close_window4(){
    document.getElementById('target4').style.display = 'none';  
}

I'm sure there is a better way than this:

function close_window(){
    $(this).parents('div').style.display='none'
}

This will close only the window that has the event, but it doesn't work.

Could someone help me please?

like image 629
Simpleacc Avatar asked Sep 02 '25 08:09

Simpleacc


1 Answers

if i understand that correctly you can simply use this:

var windows = $('#target1, #target2, #target3, #target4');
windows.on('click', function() {
  $(this).hide();
});

You should consider giving the button an class:

HTML

<div class="windows">
 <button class="close_window">X</button>
</div>

JS

var closeButtons = $('.close_window');
closeButtons.on('click', function() {
  $(this).parent().hide();
});

Then you can get actually the goal you want :-)

Regards

like image 163
Michael Schneider Avatar answered Sep 04 '25 20:09

Michael Schneider