Add a Dark Mode Toggle/Switch in WordPress Website using Elementor without Plugin

 

 

CSS code snippet for Toggle Button (inner section):

selector{
    position: fixed;
    width: 50px;
    bottom: 30px;
    right: 30px;
    cursor: pointer;
}

selector{
    --dark-border-color: #D7D7D7;
    --dark-background-color: #000000;
    --dark-icon-color: #000000;
}
.dark .dark-toggle .elementor-widget-divider .elementor-widget-container{
    background: var(--dark-background-color);
    border-color: var(--dark-border-color);
}
.dark-toggle .elementor-widget-icon{
    transition: all 0.3s ease-in-out;
}
.dark .dark-toggle .elementor-widget-icon{
    left: 24px !important;
}
.dark .dark-toggle .elementor-widget-icon .elementor-icon{
    color: var(--dark-icon-color) !important;
}

 

 

CSS code snippet for Toggle Button (icon):

selector .elementor-widget-container{
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
}
selector .elementor-icon-wrapper{
    line-height: 0;
}

 

 

JavaScript code snippet for Enabling Toggle Button:

<script>

function hasClass(element, className) {
    return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1
}

function setCookie(cname, cvalue, exdays) {
  var d = new Date()
  d.setTime( d.getTime() + ( exdays * 24*60*60*1000) )
  let expires = 'expires=' + d.toUTCString()
  document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/'
}

function getCookie(cname) {
  var name = cname + '=',
    decodedCookie = decodeURIComponent(document.cookie),
    ca = decodedCookie.split(';')
    
  for(let i = 0; i <ca.length; i++) {
    var c = ca[i]
    while (c.charAt(0) == ' ') {
      c = c.substring(1)
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length)
    }
  }
  return ''
}

document.addEventListener("DOMContentLoaded", function(){

if( getCookie('dark') == 'yes' ) {
    document.querySelector('body').classList.add('dark')    
}

document.querySelector('.dark-toggle').addEventListener('click', function(){
    
    document.querySelector('body').classList.toggle('dark')
    
    if( hasClass(document.querySelector('body'), 'dark') ) {
        setCookie('dark', 'yes', 30)
    } else {
        setCookie('dark', 'no', 30)
    }
})

})

</script>

 

 

CSS code snippet for Dark Page Background:

body.dark{
    background: #191919;
}

 

CSS code snippet for Making Dark Version Image:

.dark-image .elementor-widget-image:nth-child(1){
    margin-bottom: 0;
}
.dark-image .elementor-widget-image:nth-child(2) img{
    opacity: 0;
}
.dark .dark-image .elementor-widget-image:nth-child(1) img{
    opacity: 0;
}
.dark .dark-image .elementor-widget-image:nth-child(2) img{
    opacity: 1;
}

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *