How to add JavaScript file dynamically from JavaScript on client Side

We can add java script file on client side under head tag by JavaScript dynamically. Below is working code

            var filename = 'http://code.jquery.com/jquery-2.0.0.js';
            var fileref = document.createElement('script');
                fileref.setAttribute("type", "text/javascript");
                fileref.setAttribute("src", filename);
                fileref.setAttribute("ID", "jsScript");
                document.getElementsByTagName("head")[0].appendChild(fileref);

Let’s Understand the above code We have to put script under head tag in below format

<script src="http://code.jquery.com/jquery-2.0.0.js" type="text/javascript"></script>


So for doing this have to define filename = which can be file name and absolute and relative JS file path name.Now we have to create script element which can be done using document.createElement(‘script’) method. And for adding attribute can be used setAttribute method.


Note: Here I have also set ID property fileref.setAttribute(“ID”, “jsScript”); which is optional. It will be helpfull when you want to check whether already page contains script with this ID or not.

Below code is used for check whether already have included Js file if yes then don’t include So It can be used to Check to see if script is present before adding one.

        var jsSelector = document.getElementById("jsScript");

        if (!jsSelector) {

            var filename = 'http://code.jquery.com/jquery-2.0.0.js';
            var fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("src", filename);
            fileref.setAttribute("ID", "jsScript");
            document.getElementsByTagName("head")[0].appendChild(fileref);
        }
 

Page Keyword: How to check js file already loaded or not, add js file dynamically, add java script file by java script

Advertisements

How to Create Drag and Drop By J query.

File You need to achive dragable and dropable functionality.
jquery-1.8.2.min.js
jquery-ui-1.8.24.custom.min.js

Note: You can download this file from J-query Main Site

  $(document).ready(function () {

    $(".dragable").draggable({
        revert: "invalid" // when not dropped, the item will revert back to its initial position
    });

    $(".dropableRow").droppable({
        tolerance: "fit",
        drop: function (ev, ui) {

            //to get the id
            //ui.draggable.attr('id') or ui.draggable.get(0).id or ui.draggable[0].id
            var draggableId = ui.draggable.attr("id");
            var droppableId = $(this).attr("id");
            alert("dragable Element Id" + draggableId + " dropableId  " + droppableId);
        }
    });
});

Note : Make sure you have included these file for working drag and drop functionality:

       <!-- Have to must add without this css drag and drop will not work -->
       <!-- Make sure you have given correct path for href attribute -->
       <link type="text/css" href="Styles/jquery-ui-1.8.24.custom.css" rel="Stylesheet" />

       <!-- Have to must add without this drag and drop will not work →
       <!-- Make sure you have given correct path for src attribute -->
       <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
       <script type="text/javascript" src="Scripts/jquery-ui-1.8.24.custom.min.js"></script>

Html Code:

<body>
    <form id="form1" runat="server">

    <div id="feedBackMainForm">
           <div class="dropableMainCont">
                <div class="dropableRow" id="dropableRow1"></div>
                <div class="dropableRow" id="dropableRow2"></div>
                <div class="dropableRow" id="dropableRow3"></div>
                <div class="dropableRow" id="dropableRow4"></div>
                <div class="dropableRow" id="dropableRow5"></div>
           </div>
           <div id="items">
               <div class= "dragable" id ="item1">Text Box</div>
               <div class= "dragable" id ="item2">Label</div>
               <div class= "dragable" id ="item3">Textarea</div>
               <div class= "dragable" id ="item4">CheckBox</div>
               <div class= "dragable" id ="item5">Button </div>
           </div>
    </div>
    </form>
</body>

In abve HTML we make Text Box as dragable by Jquery function.

</pre>
 $(".dragable").draggable({
 helper: "clone",
 revert: "invalid"
 });
<pre>

and make

as dropable by calling

</pre>
$(".dropableRow").droppable({
 helper: "clone",
 accept: ".draggable",
 tolerance: "fit",
 drop: function (ev, ui) {
 // Execute Logic what ever you want here.
 }
 });
<pre>

Style Sheet:

<!-- In File Style Sheet -->
      <style type="text/css">

          #items{
             width:120px;
             height:270px;
             border:1px solid #110000;
             float:left;
          }
          .dragable
          {
            background-color: #DBDBDB;
            border:1px solid black;
            cursor: move;
            font-size: 15pt;
            height: 40px;
            line-height: 40px;
            margin: 10px;
            position: relative;
            text-align: center;
            width: 100px;
            z-index:20px;
          }
           .dropableRow{
            background-color: #DBDBDB;
            border:1px solid black;
            font-size: 15pt;
            height: 60px;
            line-height: 40px;
            margin: 4px;
            position: relative;
            text-align: center;
            width: 389px;
            float: left;
          }
          .dropableMainCont
          {
            background-color: #DBDBDB;
            border:1px solid Red;
            font-size: 15pt;
            height: 400px;
            padding:10px;
            width: 400px;
            float: left;
          }
          #feedBackMainForm
          {
              width:100%;
          }

          textarea {
             overflow:hidden;
          }
      </style>

Jquery Error: Draggable function is not defined or not found. Droppable function is not found or not defined.This error occur when you might forget to add jquery-ui-1.8.24.custom.css file

       <!-- Have to must add without this css drag and drop will not work -->
       <!-- Make sure you have given correct path for href attribute -->
       <link type="text/css" href="Styles/jquery-ui-1.8.24.custom.css" rel="Stylesheet" />

or might forget to add jquery-1.8.2.min.js or jquery-ui-1.8.24.custom.min.js file then in this case generally we get this error.

       <!-- Have to must add without this drag and drop will not work →
       <!-- Make sure you have given correct path for src attribute -->
       <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
       <script type="text/javascript" src="Scripts/jquery-ui-1.8.24.custom.min.js"></script>

How to get Dragable or Dropable element ID or attribute value in J-Query.

Some time we need to know in J-query Drag and drop functionality what are the element has dropped and There ID , and another attribute value let say get dropped element width value , height value for this you have do something like below.

    $(".dropableRow").droppable({
        drop: function (ev, ui) {

            //to get the id
            //ui.draggable.attr('id') or ui.draggable.get(0).id or ui.draggable[0].id
            var draggableId = ui.draggable.attr("id");
            var droppableId = $(this).attr("id");

            // Alert dragable elment id and dropable element Id
            alert("dragable Element Id" + draggableId + " dropableId  " + droppableId);
        }
    });

Page Keyword: Get Dragable Property value in jquery, How to get Dragable element id in jquery, How to get dragable element class name in jquery, How to know dropable ID in jquery, Get dropped element attribute in jquery.

How to call server side method by jquery or java script in asp.net.

Introduction:

Many time we come across situation to get data or perform some logic or execute function on server side by java script or j-query, so to accomplish this task on client side without posting entire page (entire page post back).

For easy understanding
Suppose you have created a login register page and you have put restriction on login name I mean login name should be unique so checking for uniqueness you must need entered login name on client side and  then you will search in database and if that login name exist it means  entered login name already exist but for doing this you have some option.

1) By Entire page post back:  After value entered in login name you need to submit user input data to perform searching by login name but this is not seems ok..isn’t it. first user will enter login name then he will check whether it is exist or not by
waiting some time so we must go for another alternative solution

2) By Ajax call: Hmmm this is what alternative method which we will look in detail here.

ASP.NET Code:

<input id="<span class=" type="text" />loginNameBox" type="text" onchange  = "GetLoginInfo()" />
<div id="<span class=">divSuccessBar"></div>
// After AJx call data will written here.
</div>

Ajax Call in js file by Java  script:


function GetLoginInfo()
{
var enteredloginName = document.getElementById("#loginNameBox").value;

$.ajax({
type: "POST",
url: "GetLoginInfo.aspx/LoginExist",
data: "{'parameter:'enteredloginName}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$("#divSuccessBar").html(msg.d);
}
});
}

Ajax Call in js file by J-query:


$(document).ready(function () {
var enteredloginName = document.getElementById("#loginNameBox").value;
$.ajax({
type: "POST",
url: "GetLoginInfo.aspx/LoginExist",
data:"{'parameter:'enteredloginName}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$("#divMainContentBar").html(msg.d);
}
});
});

url:   In ajax method url contains aspx page and webmethod which you have defined.
date : Data in ajax call in which we paas value to webmethod in server side in above
I am sending entered user name.and “parameter” which I have define in web method.


[WebMethod]
public static string IsloginExist( string parameter)
{

String isloginExist  = string.Empty;

// Check here whether entered login name exist or not.
if( //loginname exist)
{
isloginExist = "Allready Exist"
}
else
{
isloginExist = "Not Exist"
}

return isloginExist;
}

Note: You must have to reference System.Web.Services dll and place it in top like this “using System.Web.Services;”

Feel free to comment if you find any difficulty.

Another Article

C#: How to Serialize JSON Array data by c# on server side.
How to Create Drag and Drop By J query.
How to get Dragable or Dropable element ID or attribute value in J-Query.
How to call server side method by jquery or java script in asp.net.
How to add javascript file by c# code in asp.net page.
Java Script: How to Get asp.net hidden or input field value by java script/ j-Query.