Close a window with JavaScript onClick

15,022

Solution 1

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

Solution 2

You could start by making the id a parameter of the function like so:

function close_window(id) {
    document.getElementById(id).style.display = 'none';
}

That way your button's onclick would have to look something like this: "close_window('target1')"

You could also find the window to close by going up the DOM starting from the button. To give you an example for that we would need to see the actual HTML.

Solution 3

Please check the fiddle

http://jsfiddle.net/7s49z1zn/

Add a common class for the windows and close button.

$('.close').click(function(){
    $(this).parents('.window').css('display','none');

});

This should work

Share:
15,022
Simpleacc
Author by

Simpleacc

Updated on June 04, 2022

Comments

  • Simpleacc
    Simpleacc almost 2 years

    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?

  • Simpleacc
    Simpleacc over 9 years
    Not all, I only want to close 1 window (the window that I do onlcick event)
  • Simpleacc
    Simpleacc over 9 years
    The JS I must add it on the head of HTML or I can add it on a .js file?
  • Michael Schneider
    Michael Schneider over 9 years
    As you wish. I basically like to divide html from js.
  • Simpleacc
    Simpleacc over 9 years
    Yeha it's most easy with this function ^^
  • enricw
    enricw over 2 years
    This works great. Thanks!