-2

I have been using this jquery code and I want to convert this into javascript. I have recently started javascript and I have a little knowledge in jquery

<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script type="text/javascript">
  $(document).ready(function () {
    $(".row a").click(function (e) {
      e.preventDefault();
      $(".imgBox img ").attr("src", $(this).attr("href"));
    });
  });
</script>
  • I always thought that jQuery *was* JavaScript... Anyway, can you provide the HTML on which this script is applied? – trincot Mar 29 '22 at 14:03
  • You can do an online search for these jQuery functions, like "jQuery function *x* in vanilla Javascript" – mykaf Mar 29 '22 at 14:05
  • 1
    This is another useful resource: https://tobiasahlin.com/blog/move-from-jquery-to-vanilla-javascript/ – GrafiCode Mar 29 '22 at 14:10
  • My favorite tool to find the JavaScript equivalent is https://youmightnotneedjquery.com/, but it's not an automatic tool, and you need to know some JavaScript in order to convert – Christian Vincenzo Traina Mar 29 '22 at 14:13

2 Answers2

2

The equivalent in vanilla JavaScript is (I added some HTML to make it work):

document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll(".row a").forEach(function(elem) {
        elem.addEventListener("click", function (e) {
            e.preventDefault();
            document.querySelector(".imgBox img").src = elem.href;
        });
    });
});
<div class="row">
    <a href="https://dummyimage.com/600x120/000/fff">link 1</a>
</div>
<div class="row">
    <a href="https://dummyimage.com/600x120/00f/f88">link 2</a>
</div>
<div class="imgBox"><img src=""/></div>
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Can you explain this code part by part Im new to js – Private Xoxo Mar 29 '22 at 14:37
  • It does what your jQuery code did - so that should explain what this code does? All these methods are explained on mdn: [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener), [querySelectorAll](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll), [forEach](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach), [querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) – trincot Mar 30 '22 at 05:27
0

Following instruction from this cheatsheet: https://tobiasahlin.com/blog/move-from-jquery-to-vanilla-javascript/

const ready = (callback) => {
  if (document.readyState != "loading") callback();
  else document.addEventListener("DOMContentLoaded", callback);
}

ready(() => { 
  /* Do things after DOM has fully loaded */
  document.querySelector(".row a").addEventListener("click", (e) => {
    e.preventDefault();
    document.querySelector(".imgBox img ").setAttribute('src', document.querySelector(".imgBox img ").getAttribute('href));
  });
});
GrafiCode
  • 3,307
  • 3
  • 26
  • 31