Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<div> onClick not working?

Iam printing some content using php code inside html but, when i tried to click on that div its not calling the function in onClick ??

Here is my php code

 echo '<div class="col-sm-12 col-xs-12 " ><div class="row ">';
echo '<div class="col-sm-10" onClick="openUrlInNewTab("'.$myarray['Job']['link'].'");"><h3>';
echo  $myarray['Job']['title']."</h3></div></div></div>";

this is resulting html code in "view source" of browser

<div class="col-sm-12 col-xs-12 ">
 <div class="row " >
  <div class="col-sm-10 " onClick="openUrlInNewTab("www.example.com");" >
    <h3>Can you Code? </h3>
  </div>
 </div>
</div>

and here is my function in html page

    function openUrlInNewTab(url) {
// div click is not reaching  here
     alert(url); 
     window.open(url, "_blank");
}
like image 232
user3755198 Avatar asked Dec 12 '22 04:12

user3755198


1 Answers

You should use single quotes.

Instead of

<div class="col-sm-10 " onClick="openUrlInNewTab("www.example.com");" >

you should have

<div class="col-sm-10 " onClick="openUrlInNewTab('www.example.com');" >

If you put double quotes inside double quotes it simple won't work.

So in PHP you should change:

 echo '<div class="col-sm-10" onClick="openUrlInNewTab("'.$myarray['Job']['link'].'");"><h3>';

into

echo '<div class="col-sm-10" onclick="openUrlInNewTab(\''.$myarray['Job']['link'].'\');"><h3>';

EDIT

One extra thing. If you want this url open in your browser, you should rather add http:// before www.example.com

Sample working HTML code:

<!DOCTYPE html>
<head>
    <meta charset="utf-8" />
</head>
<body>
<div class="col-sm-12 col-xs-12 ">
 <div class="row " >
  <div class="col-sm-10 " onclick="openUrlInNewTab('http://www.example.com');" >
    <h3>Can you Code? </h3>
  </div>
 </div>
</div>
          <script>
    function openUrlInNewTab(url) {
// div click is not reaching  here
     alert(url); 
     window.open(url, "_blank");
}
</script>
</body>
</html>
like image 102
Marcin Nabiałek Avatar answered Dec 23 '22 00:12

Marcin Nabiałek