Execute JavaScript code when clicking link within DIV

1

I have this javascript code:

<script type="text/javascript">
    var domain = '<?=$x['host']?>';
    var auto_surf = <?=($site['surf_type'] == 1 ? 0 : 1)?>;
    var sid = '<?=$sit['id']?>';
    var hash = '<?=MD5(rand(1000,9999))?>';
    var barsize = 1;
    var maxbarsize = 250;
    var numbercounter = <?=$surf_time?>;
    var numbercounter_n = <?=$surf_time?>;
    var adtimer = null;
    var focusFlag = 1;
    var fc_override = <?=($site['surf_fc_req'] == 1 ? 0 : 1)?>;
    var fc_skip = <?=($site['surf_fb_skip'] == 1 ? 1 : 0)?>;
    var buster_listener = 1;
    var buster = 0;
    var buster_red = '?skip=<?=$sit['id']?>&bd';
    var surf_file = 'surf.php';
    var can_leave = <?=($sit['id'] == 0 ? 'true' : 'false')?>;
    var report_msg1 = '<?=mysql_escape_string($lang['b_277'])?>';
    var report_msg2 = '<?=mysql_escape_string($lang['b_236'])?>';
    var report_msg3 = '<?=mysql_escape_string($lang['b_237'])?>';
    window.onbeforeunload = <?=($site['surf_fb_skip'] == 1 ? 'bust' : 'function () {if (can_leave == false) {var a = "";var b = b || window.event;if (b) {b.returnValue = a;}return a;}}')?>;
</script>

But I want to execute this code by clicking on a link within that DIV:

<div class="fb-post" onclick="test()" data-href="<?=($sit['url'] == '' ? ($site['surf_type'] != 1 ? 'system/modules/surf/nocoins.html' : 'system/modules/surf/nopage.html') : hideref($sit['url'], ($site['hideref'] == 1 ? 1 : ($site['hideref'] == 2 ? 2 : 0)), (empty($site['revshare_api']) ? 0 : $site['revshare_api'])))?>" data-width="750" data-show-text="false"></div>
    
asked by anonymous 03.05.2016 / 17:50

1 answer

0

You have to register an event to be monitoring the click action on your div . Note that all elements that have the className are being tracked as fb-post , where className matches the class tag of your div tag.

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('.fb-post').addEventListener('click', function() {
    // coloque o seu código aqui dentro
  })
});

I strongly recommend that you do not mix PHP with JavaScript . Also search the term Non-Obstructive JavaScript and Semantic HTML .

    
03.05.2016 / 18:15