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'