-5

Is there any method to transform jQuery click event (see below) into regular JavaScript function?

    $('#lcSitemapCategory').click(function() {
        var hiddenField = $('#lcSitemapCategoryHidden'),
        val = hiddenField.val();
        hiddenField.val(val === "true" ? "false" : "true");
        $('#lcSitemapCategory').val(val === "true" ? "false" : "true")
    });
  • 2
    Try https://youmightnotneedjquery.com. It lets you look up jQuery methods to get native JS implementations. If you have a specific issue converting this code please post your attempt so that we can help you debug it – Rory McCrossan Aug 02 '22 at 12:51
  • I already tried a couple of online converters, but they all don't work for me. – Robert Baumann Aug 02 '22 at 13:22
  • Closed already, but, given the additional information comment below, this would be closed as a duplicate of: [event binding on dynamically created elements](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Aug 02 '22 at 15:38

1 Answers1

0

This version works:

let element = document.getElementById("lcSitemapCategory");

element.addEventListener("click", function() {
    var hiddenField = $('#lcSitemapCategoryHidden'),
    val = hiddenField.val();
    hiddenField.val(val === "true" ? "false" : "true");
    $('#lcSitemapCategory').val(val === "true" ? "false" : "true")
});
  • The content within the click handler are still using jQuery – Rory McCrossan Aug 02 '22 at 13:43
  • Yes, but it is uncritical because jQuery framework is still loaded, but dynamically loaded and this kind of loading was the problem first when a place the code within HTML body. Now, it works. – Robert Baumann Aug 02 '22 at 13:55
  • @RobertBaumann in that case you should just wrap your code in doc.ready: `$(() => { $('#lcSitemapCategory').click(function() { ... }); });` or (more likely) use event delegation: `$(document).on("click", "#lcSitemapCategory", function() {...` – freedomn-m Aug 02 '22 at 15:36
  • Wait, jquery is *dynamically loaded*? How strange. Guess at least you got something to work - how do you know jquery has loaded when the user clicks? You should review modern browser js caching and loading from a CDN (hint: jquery will very likely already be loaded and cached *parsed* on your site, so there would be zero load for most users). – freedomn-m Aug 02 '22 at 15:38
  • There is nothing to work. The only problem by loading jquery dynamically is that I can't place jQuery code within html body, because this code is parsed before jquery is parsed and that's why I searched vor a native way to place Javascript within HTML body. I needed this solution, because I use Smarty and a foreach loop to generate ID's within Javascript code dynamically. – Robert Baumann Aug 02 '22 at 17:38
  • @freedomn-m $(document).ready(function() doesn't work if jQuery is loaded dynamically because $(document).ready(function() itself is jQuery code. – Robert Baumann Aug 03 '22 at 08:20