0

I’m working in adding an onclick attribute to a few links on my drupal 7 site. I added the menu_attributes module to assign an id to my links, tried adding the following code to a new js file I included in sites/themes/themeName.info.

function() {
  var link = document.getElementById('conversion');
  //link.setAttribute("target", "_blank");
  link.addEventListener("click", function(e){
        return gtag_report_conversion('http://www.mysite/page’); }); }

It’s not adding onclick, would greatly appreciate any help.

hvannia
  • 1
  • 2

2 Answers2

0

Check whether the script is loading in the page. See this for the details of adding javascript in drupal 7.

Meera
  • 170
  • 7
  • I included the 'Add to Head' module to add the other .js scripts. This one I've been trying to test it in developer console. I get the element but the error occurrs when trying to add "onclick()" – hvannia Nov 09 '18 at 04:04
  • $('#conversation').on('click',function(){ //Code here } Could you try this? – Meera Nov 09 '18 at 04:08
  • I found this link, I think this is my issue, the script is looking for something not yet existing, https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element . Option 1 did not work for me. – hvannia Nov 10 '18 at 14:59
0

Based on JavaScript that executes after page load and adjusted for this specific problem this code works if placed inside head

function addClick(){
                    alert('click'); //confirm it works
                    return gtag_report_conversion('http://mySite/myPage');
                }

                 //make sure this runs after dom is loaded.. so element can be found
                 document.addEventListener("DOMContentLoaded", function(){
                    var link = document.getElementById("cteconversion");
                    link.onclick=addClick;
                 });
hvannia
  • 1
  • 2