Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Sunday 26 March 2017

How to call a function before leaving page - Jquery beforeonunload



Hi guys, Shraing Code Snippet for Calling a function before leaving page. It may be required for variety of purposes. you can use it to track statistics for user's leaving from a website page to record that page for bounce pages statistics from where user is leaving website mostly. this is just a simple example you can use it for variety of way.

you can share in comments for which purpose you may require this type of code functionality.

**Jquery Code Example -**

    $(window).bind('beforeunload', function(){
      Func_ToInsert_Record();
      Alert('Thanks And Bye!');
    });

**Javascript Code Example -**


    // Anonymous function
    window.onbeforeunload = function(event) {
      var message = '';
      if (window.event) {
        console.log(window.event);
        console.log(event.currentTarget.performance);
        console.log(event.currentTarget.performance.navigation);
        console.log(event.currentTarget.performance.navigation.type);
       
      }
     
      event = event || window.event;
      event.preventDefault = true;
      event.cancelBubble = true;
      event.returnValue = message;
    }


Saturday 27 August 2016

Javascript Event Propagation vs Event PreventDefault


Event Propagation vs Event PreventDefault

Event Propagation

Event Propagation Stops the Event from bubbling or making the event Chain . 

Example : -  A Click Event on a <td> tag will also fire click event on it's parent <tr> and this event chain also continues to parent <table> tag of that <tr> this makes a event chain in order to stop this event Chain propagation we can Use StopPropagation that Prevents this from happening.

StopPropagation ( ) will stop that event from happening on parent (the entire ancestors). When We Use StopPropagation only < td > Event will fire as per our Example above its parent < tr > or            < table > Click event will not fire .

StopPropagation ( ) Tells downward propagation of the event is stopped and also its upward propagation

Event PreventDefault

Event PreventDefault () Prevents the Default Browser Action In Response the Event Triggered . The preventDefault method prevents an event from carrying out its default functionality

Example : If we want to Stop Form Submit on click of Submit Button in form we can use PreventDefault to stop the default form submit behaviour of submit button in form .

As its name tells it just prevent occurence of the default behavior of event like if you need to prevent the click to occur on click event or stop entering of symbols in textbox if its character then make a check it entered character is symbol on keypress press and execute preventdefault ( ) to prevent default behavior of execution of  event on keypress and nothing will enter in textbox if its symbol .



CODE EXAMPLE For StopPropagation


<div onclick='executeParent()'>
<a href='http://google.com'>Click here to visit google.com</a>
</div>
<script>
$('a').click(function(event) {
event.stopPropagation();
$('a').text('Click event is going to be executed');
$('a').contents().unwrap();
});
function executeParent() {
alert('here');
}
</script>


CODE EXPLANATION For StopPropagation


If you execute the code above, the function executeParent() will not be called and you will not get the javascript alert this time. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit google.com‘ replaced by the text ‘Click event is going to be executed‘ and immediately you will be redirected to google.com. This is because we haven’t prevented the default click action from triggering this time using event.preventDefault() method.


CODE EXAMPLE For PreventDefault


<div onclick='executeParent()'>
<a href='http://google.com'>Click here to visit google.com</a>
</div>
<script>
$('a').click(function(event) {
event.preventDefault();
event.stopPropagation();
$('a').text('Click event prevented');
$('a').contents().unwrap();
});
function executeParent() {
alert('here');
}
</script>


CODE EXPLANTION For PreventDefauls

If you execute the code above, the function executeParent() will not be called and you will not get the javascript alert. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit google.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to google.com. This is because we have prevented the default click action from triggering this time using event.preventDefault() method.



Thursday 11 August 2016

Angularjs Vs Jquery


Answer Angularjs Vs Jquery On Quora 
Angularjs Vs Jquery

jQuery will be used for things like higher level APIs, updating DOM elements, adding classes and wrapping XHR calls up nicely. Angular 1.x actually uses jQuery lite (jQLite) inside itself, or can use the full jQuery library if it's present before Angular at runtime. Using jQuery with Angular will unleash more power to Angular core as it knows you're using it, so it binds onto jQuery and passes you the full jQuery API instead of it's built-in jQLite.Remember that Angular is a data-binding MVVM framework, of which jQuery is not.

See The Major Benefits in Angular JS as Compared To Jquery

Below is Table List of Difference between jquery and Angularjs . See the Point search what that point means then analyze do you need the power or usage of that point in the project . On the basis of that Analyze Which one of them you need in your project

Difference between on and bind in jQuery


The .bind() method registers the event and event handler directly to the DOM element.This method is still very handy when wiring-up event handlers, but there are various performance concerns as are listed below.
Internally .bind() maps to .on() as per current version of Jquery .bind may be removed from future versions at any time. There is no reason to keep using .bind and every reason to prefer .on instead.
The .bind() method will attach the event handler to all of the anchors that are matched! That is not good. Not only is that expensive to implicitly iterate over all of those items to attach an event handler, but it is also wasteful since it is the same event handler over and over again.

Problems
  1. The method attaches the same event handler to every matched element in the selection.
  2. It doesn’t work for elements added dynamically that matches the same selector.
  3. There are performance concerns when dealing with a large selection.
  4. The attachment is done upfront which can have performance issues on page load.
The on() method as being “overloaded” with different signatures, which in turn changes how the event binding is wired-up. The .on method bring a lot of consistency to the API and hopefully makes things slightly less confusing.

Cons 1. Brings confusion because the behavior changes based on how you call the method.

Thursday 12 May 2016

Create News Feed In PHP


Code To Create A Simple News Feed In PHP


Use Ajax & Jquery To Fetch & Populate News Feed . Make Ajax Call From Page Control Will go to specified PHP page through ajax call then fetch data in that PHP page and send data to callback to Ajax Call

See A simple Example below :-

HTML PAGE CODE

<html>
<head>
//Required CSS  / JSS Files
</head>
<body>
<div id="news"></div>
//Click Button Below To Fetch News Feeds
<input type="button" onclick="GetNews()" value="Get News Feed" />
<script>
    function GetNews()
    {
        $("#news").load("path_to/AjaxFetchData.php")
    }
</script>
</body>
</html>


AjaxFetchData.php File Code


//Sql Query To Fetch News Feed From Database
$con= Initialize it with connection Details for database
$sql = "Select Top 50 from TblNews";
$result = $result=mysqli_query($con,$sql);
while($row =  $result->fetch_assoc())
{
    echo("<div class='NewsFeed'>");
    echo("<div class='title'>" . $row['title'] . "</div>");
    echo("<div class='body'>" . $row['body'] . "</div>");
    echo("</div>");



}

Saturday 30 April 2016

Parse Json file In Jquery Ajax


See Running Demo Here -Demo For Parsing Json File In Jquery


Json File Data

 [
    {
        "alignment1": "TM"
    },
    {
        "alignment2": "TLBR"
    },
    {
        "alignment3": "BL"
    },
    {
        "ruleTimer": "6"
    },
    {
        "music": "Enable"
    },
    {
        "rule1": "Rule 1"
    },
    {
        "rule2": "Rule 2"
    },
    {
        "rule3": "Rule 3"
    },
    {
        "rule4": "Rule 4"
    },
    {
        "ID1": "p7ZsBPK656s"
    },
    {
        "name1": "Disfigure - Blank [NCS Release]"
    },
    {
        "ID2": "__CRWE-L45k"
    },
    {
        "name2": "Electro-Light - Symbolism [NCS Release]"
    },
    {
        "ID3": "J2X5mJ3HDYE"
    },
    {
        "name3": "DEAF KEV - Invincible [NCS Release]"
    },
    {
        "color1": ""
    },
    {
        "color2": ""
    },
    {
        "color3": ""
    },
    {
        "color4": ""
    },
    {
        "color5": ""
    }

]


Index.html Code 

 <!doctype html>
<html>
<head>

    <title>How to Parse a JSON file using jQuery</title>
   
    <style>
        body{
            text-align: center;
            font-family: arial;
        }

        .button{
            margin:20px;
            font-size:16px;
            font-weight: bold;
            padding:5px 10px;
        }
    </style>


</head>
<body>
    <a href="data.json" target="_blank">Open JSON file</a><br />
    <input type="button" value="Get and parse JSON" class="button" />
    <br />
    <span id="results"></span>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

    <script>

        //When DOM loaded we attach click event to button
        $(document).ready(function() {
           
            //after button is clicked we download the data
            $('.button').click(function(){

                //start ajax request
                $.ajax({
                    url: "data.json",
                    //force to handle it as text
                    dataType: "text",
                    success: function(data) {
                       
                        //data downloaded so we call parseJSON function
                        //and pass downloaded data
                        var json = $.parseJSON(data);
                        //now json variable contains data in json format
                        //let's display a few itemscons
                        console.log("data is - "+json);
                       
                       // $.each(json, function(idx, obj) {

//$.each(obj, function(idx, obj) {
//console.log("one-"+obj+" "+idx);
//$('#results').append("<strong>"+obj+"</strong> :- "+idx+"<br/><br/>");
//});
//});


function Iterate(data)
{
    jQuery.each(data, function (index, value) {
        if (typeof value == 'object') {
            //alert("Object " + index);
            Iterate(value);
        }
        else {
             alert(index + "   :   " + value);
             $('#results').append("<strong>"+index+"</strong> :- "+value+"<br/><br/>");
        }
    });

};

Iterate(json);
                       
                      //  $('#results').html('Plugin name: ' + json.alignment1);
                    }
                });
            });
        });
    </script>

</body>

</html>