Home  >  Q&A  >  body text

Rails Javascript - Converting jQuery to Javascript not working using Rails 7

Rails 7 with Turbo/Hotwire. I'm reusing code copied from an old project from 2018. This code/jQuery is for the information popup:

$(document).ready(function() {
      $('#info').hover(function() {
        $('#popup').show();
        }, function() {
        $('#popup').hide();
        });
      });

After rewriting the javascript (correct?), this is what I'm currently testing - without success:

$(document).addEventListener("DOMContentLoaded", function() {
      $('#info_1').onmouseover(function() {
        $('#popup_1').show();
        }, function() {
        $('#popup_1').hide();
        });
      });

I have #info_1 / id=info_1 In a div, popup #popup_1 / id=popup_1 Directly below another div.

I've tested placing the javascript in the app/javascript/custom/menu.js file, as well as using it in the tag on the view page.

How should I handle this.

Thanks

P粉436688931P粉436688931276 days ago472

reply all(1)I'll reply

  • P粉846294303

    P粉8462943032024-01-17 17:24:23

    $() means you are still using jquery, you have not converted it to pure JavaScript, but you have converted it to broken jquery. Every line using the $().someChained function needs to be replaced. For example:

    $(Documentation).addEventListener

    should be

    Documentation.addEventListener

    This is the gist of what you want, there is a note to note about DOMContentLoaded, if it loads before the listener is bound it will never fire.

    document.addEventListener('DOMContentLoaded', function() {
      var info = document.getElementById('info');
      var popup = document.getElementById('popup');
    
      info.addEventListener('mouseenter', function() {
        popup.style.display = 'block';
      });
    
      info.addEventListener('mouseleave', function() {
        popup.style.display = 'none';
      });
    });

    Side note, if you need to replace a non-trivial project jquery with plain js, and you are not familiar with the language at all, then this is going to be a very, very difficult task.

    reply
    0
  • Cancelreply