0

So, I have been trying to, just for knowledge's sake, convert some of my jQuery into plain, vanilla javascript. I'd just like to get some comments on if there is a better way I could have re-written this. (It's also in coffeescript.)

The script itself listens for click events on the element for example, finds the with the same ID as the data-modal element and then attaches a class to that element, which makes a window pop up, basically. Then, the overlay class listens for a click event, which removes the previously attached class 'md-show' from any that has it. It's just a simple script really, that adds and removes a class in order to show a popup window.

Thanks for any and all help.

Here is the original jQuery:

    overlay = $('.md-overlay')
$('.md-trigger').click (e) ->
    modal = $(@).data 'modal'
    modalID = '#' + modal
    $(modalID).addClass 'md-show'
    e.preventDefault()
$('.md-close').click ->
    $("div[id^='modal']").removeClass 'md-show'
overlay.click ->
    $("div[id^='modal']").removeClass 'md-show'

And here is the conversion to vanilla js:

    hasClass = (el, cl) ->
    regex = new RegExp('(?:\\s|^)' + cl + '(?:\\s|$)')
    !!el.className.match(regex)

overlay = document.getElementsByClassName('md-overlay')[0]
triggers = document.getElementsByClassName('md-trigger')
modals  = document.querySelectorAll("div[id^='modal']")

for i in [0...triggers.length]
    trigger = triggers[i]
    trigger.addEventListener 'click', (e) ->
        modal = this.getAttribute 'data-modal'
        modalID = document.getElementById(modal)
        modalID.classList.add 'md-show'
        return false

overlay.addEventListener 'click', ->
    for i in [0...modals.length]
        eachModal = modals[i]
        if hasClass(eachModal, 'md-show')
            eachModal.classList.remove 'md-show'

1 Answer 1

1

CoffeeScript takes care of proper iteration through an array for you. So

for i in [0...triggers.length]
    trigger = triggers[i]
    trigger.addEventListener 'click' ...

can be written more concisely as:

for t in triggers
    t.addEventListener 'click' ...
Sign up to request clarification or add additional context in comments.

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.