0

Trying to implement onclick tag load for multiple button components in AEM Need suggestion on bestpractices. below is the method I have implemented. Can some one please help me with this. Thanks in advance!

<sly data-sly-test="${properties.tag}">
    <script>
        $(".input1-tag").click(function(e){
            e.preventDefault();
            var href = $(this).attr("href");
            $("body").append("<img src=\" ${properties.tag @ context ='scriptString'} \" width="1" height="1" alt="" />");
            window.location = href;
        });
    </script>
</sly>

<sly data-sly-test="${properties.optionaltag}">
   <script>
     $(".input2-tag").click(function(e){
        e.preventDefault();
        var href = $(this).attr("href");
        $("body").append("<img src=\" ${properties.optionaltag @ context ='scriptString'} \" width="1" height="1" alt="" />");
        window.location = href;
      });
   </script>
</sly>

<sly data-sly-test="${properties.thirdtag}">
   <script>
      $(".input3-tag").click(function(e){
        e.preventDefault();
        var href = $(this).attr("href");
        $("body").append("<img src=\" ${properties.thirdtag @ context ='scriptString'} \" width="1" height="1" alt="" />");
        window.location = href;
     });
   </script>
</sly>
Ravi
  • 91
  • 1
  • 8
  • Can you please clarify the `implement onclick tag load for multiple button ` part? What are you trying to achieve exactly by these click functions? Is this in particular authoring UI or your application? – Imran Saeed Aug 28 '18 at 13:05
  • @ImranSaeed This is for application, on user click before taking them to the destination page thru img source will load a double click tacking url. Here I have 3 buttons so will be taking three double click urls from user and load it on click. – Ravi Aug 28 '18 at 13:18

1 Answers1

0

Looks more of a code review request - Apt for https://codereview.stackexchange.com/

But since you are here, I can think of the following -

  • Move the script code to a .js file in clientlibs. The main aim of sightly or HTL is to beautify the HTML markup and separate presentation and logic concerns.
  • Use sling models to retrieve property values.
  • Have a placeholder tag in the <body> section and append to it instead of directly to the <body> tag, gives you more control on positioning the element to a different location later on.
  • If you foresee more events to the input tags, use an event listener instead of inline events. Event listener vs on click - More info here.
  • Since all you are doing while appending the <img> tag is just modify the src attribute, you could have <img> tag already baked in the markup, hidden initially maybe and use attr() function to set the src attribute.
SubSul
  • 2,523
  • 1
  • 17
  • 27