user6261443
user6261443

Reputation:

JQuery call popup

I am an Apprentice and never worked with Javascript. My Javascript function calls a popup. This works on the first button but doesn't work on all the following and since the application is constantly adding buttons(same class) I cannot hardcode. I guess ther will be a solution with JQuery... ("open") and ("openPopupUseExisting") are the two buttons.

<script type="text/javascript">
    window.onload = function () {
        document.getElementById('blackout').addEventListener('click', function () {
            document.getElementById('popup').className = "";
            document.getElementById('blackout').className = "";
            document.getElementById('popupUseExisting').className = "";
        }, false);
        document.getElementsByClassName("open")[0].addEventListener('click', function () {
            document.getElementById('popup').className = 'visable';
            document.getElementById('blackout').className = 'visable';
        }, false);
        document.getElementsByClassName("openPopupUseExisting")[0].addEventListener('click', function () {
            document.getElementById('popupUseExisting').className = 'visable';
            document.getElementById('blackout').className = 'visable';
        }, false);
        document.getElementsByClassName("close")[0].addEventListener('click', function () {
            document.getElementById('popup').className = "";
            document.getElementById('blackout').className = "";
            document.getElementById('popupUseExisting').className = "";
        }, false);
    };
</script>

Upvotes: 1

Views: 112

Answers (2)

Filipe Merker
Filipe Merker

Reputation: 2446

Friend, you don't need to add an entire library just in order to bind dynamically added elements.

You can bind the document for click event, and then check if the clicked element is the one you want. It prevent dynamically added elements to be unbound, since it aims for the entire document.

document.addEventListener('click', function (e) {
    if (e.target.classList.contains('blackout')) {
        // your fancy magic with .blackout
    } else if (e.target.classList.contains('open')) {
        // your fancy magic with .open
    }
}, false);

If you really want to use jQuery, as you ordered, it's quite simple, use the on method

$('.open').on('click', function(){
  // your fancy magic with .open
});

Upvotes: 0

Quentin
Quentin

Reputation: 944256

document.getElementsByClassName("close")[0]

See that 0?

getElementsByClassName returns an array-like object. You are getting the first item off it.

Loop over it with a for loop.

Upvotes: 2

Related Questions