Close a window with JavaScript onClick
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
Add a common class for the windows and close button.
$('.close').click(function(){
$(this).parents('.window').css('display','none');
});
This should work
Simpleacc
Updated on June 04, 2022Comments
-
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 over 9 yearsNot all, I only want to close 1 window (the window that I do onlcick event)
-
Simpleacc over 9 yearsThe JS I must add it on the head of HTML or I can add it on a .js file?
-
Michael Schneider over 9 yearsAs you wish. I basically like to divide html from js.
-
Simpleacc over 9 yearsYeha it's most easy with this function ^^
-
enricw over 2 yearsThis works great. Thanks!