Daniel Brown
Daniel Brown

Reputation: 3062

Avoid inline javascript

My code is essentially this:

<a href="javascript:void(0);" onClick="viewServices(1)">Services</a>
<a href="javascript:void(0);" onClick="viewServices(43)">Services</a>
<a href="javascript:void(0);" onClick="viewServices(16)">Services</a>
...

Where viewServices:

function viewServices(stylistID){
    alert(stylistID);
}

Only, there are two problems:

  1. I am using inline Javascript, and that is discouraged.
  2. When I click a link, the function isn't called.

It should also be mentioned that I am importing JQuery and Bootstraps .js files, and that each link (as well as associated ID) is loaded dynamically.

Is there an established method that will allow me to remove my inline javascript, but also make it so that I can call functions that pass the dynamically loaded link's "ID" to the function?

** EDIT

Each link is generated during a mysqli_fetch_row that repeats until each row's information has been run through. The number in viewServices(#) is actually

<?php echo $row[0]; ?>

Upvotes: 2

Views: 387

Answers (3)

Oriol
Oriol

Reputation: 287970

You could use

<a class="viewServices" data-arg="1">Services</a>
<a class="viewServices" data-arg="43">Services</a>
<a class="viewServices" data-arg="16">Services</a>

and

// viewServices is not defined here
(function() { // viewServices is defined inside here
    function viewServices(arg) { /* ... */ }
    function viewServicesCaller() {
        viewServices(this.getAttribute('data-arg'));
    }
    var els = document.getElementsByClassName('viewServices');
    for(var i=els.length-1; i>=0; --i) {
        els[i].onclick = viewServicesCaller;
    }
})();

Probably, your code doesn't work because viewServices is defined inside a closure, so it isn't global. Then, you must add the event listeners in that closure.

Upvotes: 2

Billy Chan
Billy Chan

Reputation: 24815

A solution is to utilize data attribute and class to refactor html like this

<a href="#" data-service="16" class="service-link">Services</a>

Then, jQuery

$('.service-link').on('click', function(e){
  e.preventDefault(); // Stop default behavior of clicking link
  alert(this.data('service')); // Retrieve the service id and use it
});

Upvotes: 6

Progo
Progo

Reputation: 3490

What errors are you getting in the console?

Is the javascript in the head section of your page? If not, try that.

If you don't want to do that, make sure the javascript code is before the link.

Good luck.

For jQuery, you could do this:

<a class="services" data-service="1">Services</a>
<a class="services" data-service="43">Services</a>
<a class="services" data-service="16">Services</a>


$(".services").click(function(link){
  link.preventDefault();
  alert(this.data("service-id"));
});

Upvotes: 1

Related Questions