user1467439
user1467439

Reputation: 389

How can I convert this function from jquery to pure javascript?

I have tried a lot of permutation, I am too dependent on jquery and for this particular assignment I have to do without...

I am now stuck and cannot convert this to work with pure javascript:

			$.root_ = $('body');
			$.root_.on('click', '[data-action="toggle"]', function(e) {
			  var $this = $(this),
			    element = $(this).attr("data-target") || 'body';
			  $(element).toggleClass($(this).attr("data-class"));
			  //clear memory reference
			  $this = null;
			  element = null;

			  //save settings
			  //saveSettings();

			});
.red-bg {
  background: #3d1c24;
}
.white-bg {
  background: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>

<head></head>

<body>

  <a href="#" data-action="toggle" data-class="red-bg">Change BG (RED)</a><br>
  <a href="#" data-action="toggle" data-class="white-bg">Change BG (WHITE)</a>

</body>

</html>

Upvotes: 1

Views: 139

Answers (2)

Jaromanda X
Jaromanda X

Reputation: 1

document.body.addEventListener('click', function(e) {
    var target = e.target;          // convenience
    var dataset = target.dataset;   // convenience
    var selector, element;
    if (dataset.action == 'toggle') {
        selector = dataset.target || 'body';
        element = document.querySelector(selector);
        if (element) {
            element.classList.toggle(dataset['class']);
        }
    }
    //save settings
    //saveSettings();
});

NOTE this uses node.classList and node.querySelector which probably doesn't work on old IE (older than 11 - don't know, do some research) - but you can get workarounds for for such old tech

NOTE: If the element targeted by the dataset.target can result in multiple elements - do this instead

document.body.addEventListener('click', function(e) {
    var target = e.target;          // convenience
    if (target.dataset.action != 'toggle' && target.parentNode.dataset.action == 'toggle') {
        target = target.parentNode;
    }
    var dataset = target.dataset;   // convenience
    var selector, elements;
    if (dataset.action == 'toggle') {
        selector = dataset.target || 'body';
        elements = document.querySelectorAll(selector);
        if (elements.length) {
            [].forEach.call(elements, function(element) {
                element.classList.toggle(dataset['class']);
            });
        }
    }
    //save settings
    //saveSettings();
});

Upvotes: 3

document.querySelector('[data-action="toggle"]').onclick = function() {}

and functions like getElementsByClassName and hasClass addClass

Upvotes: -1

Related Questions