Reputation: 237
I have this code In my MasterPage.master
<head runat="server">
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="<%# ResolveUrl("~/") %>script.js" ></script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<div class="handle">Click me</div>
</body>
I have this code in my script.js file
$('.handle').on('click', function () {
alert('hello world');
});
When I click the div section, I don't have alert message as i am supposed to have.
I have this code in my Default.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainContent" Runat="Server">
</asp:Content>
This is my project directory in visual studio
Upvotes: 1
Views: 1107
Reputation: 3684
You execute your JavaScript before the DOM is created. Change your script.js code to
$(document).ready(function () {
$('.handle').on('click', function () {
alert('hello world');
});
});
jQuery live/on only works after loading of the DOM is finished. As an alternative put your JavaScript code after the div-declaration.
Upvotes: 1
Reputation: 11
I have tried your code and it seems to be fine to me. Let me share with you that code.
MasterPage.master:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<div class="handle">Click me</div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
<script type="text/javascript">
$('.handle').on('click', function () {
alert('hello world');
});
</script>
Default.aspx:
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>
Upvotes: 0