Google+ Peter Bromberg's .NET Blog | Jquery

Peter Bromberg's .NET Blog All Things Programming

How to Ensure that jQuery is only loaded once

26. July 2016 13:50 by admin in ASP.NET, C#, Jquery

Often we have pages and master pages and "bundles" that load scripts like jQuery and we can't always be sure that a particular page already has it loaded. Here is a script that will only inject jQuery into a page if it has not already been loaded:

<HTML>
<HEAD>

<!-- comment or uncomment next line to test it out --->
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>

<script>

// Only do anything if jQuery isn't defined

if (typeof jQuery == 'undefined') {

function getScript(url, success) {

var script = document.createElement('script');

    script.src = url;

var head = document.getElementsByTagName('head')[0],done = false;

// Attach handlers for all browsers

script.onload = script.onreadystatechange = function() {

if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {

done = true;

// callback function provided as param

success();

script.onload = script.onreadystatechange = null;

head.removeChild(script);

};

};

head.appendChild(script);

};

 

getScript('https://code.jquery.com/jquery-3.1.0.min.js', function() {

if (typeof jQuery=='undefined') {

// Super failsafe

} else {

alert("We Loaded it!");

// jQuery loaded 

}

});

 

} else { 

// jQuery was already loaded

alert("jQuery is Already Loaded!");

// Run your jQuery Code

};

</script>

</HEAD>

<BODY>

</BODY>

 

</HTML>

 

How to Filter (Search) in a Table With jQuery

25. October 2013 11:28 by admin in Jquery

Click here for Working Sample

<!DOCTYPE html> 
<html > 
<head><meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>JQuery Table Search Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery.expr[':'].contains = function(a,i,m){
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
$(document).ready(function(){
$('input[name="search"]').keyup(function(){
var searchterm = $(this).val();
if(searchterm.length >2) {
var match = $('tr.data-row:contains("' + searchterm + '")');
var nomatch = $('tr.data-row:not(:contains("' + searchterm + '"))');
match.addClass('selected');
nomatch.css("display", "none");
} else {
$('tr.data-row').css("display", "");
$('tr.data-row').removeClass('selected');
}
});
});
</script>
<style type="text/css">table {background-color: #FAF3DF;}table tr.data-row {background-color: #fff;}table tr.data-row td.selected-cell {color: #fff;background-color: #660000;}table tr.data-header {background-color: #F1EDE3;border-bottom: solid 2px #fff;font-weight: bold;}table tr.selected {background-color: #FFCC88;} </style></head> <body><p>Search term:<input type="text" name="search" /></p><table cellspacing="4"><tr class="data-header"><td>Contacts</td></tr><tr class="data-row"> <td>Jerald Mickey</td></tr><tr class="data-row"> <td>Minda Carlen</td></tr><tr class="data-row"> <td>Marlene Nida</td></tr><tr class="data-row"> <td>Daysi Cassano</td></tr><tr class="data-row"> <td>Bonny Medford</td></tr><tr class="data-row"> <td>Patria Sciortino</td></tr><tr class="data-row"> <td>Kathaleen Herwig</td></tr><tr class="data-row"> <td>Junior Chamberlin</td></tr><tr class="data-row"> <td>Belkis Fleishman</td></tr><tr class="data-row"> <td>Evangeline Ishee</td></tr><tr class="data-row"> <td>Reyes Newland</td></tr><tr class="data-row"> <td>Eleonore Federico</td></tr><tr class="data-row"> <td>Briana Launius</td></tr><tr class="data-row"> <td>Eula Bernard</td></tr><tr class="data-row"> <td>Albert Palm</td></tr><tr class="data-row"> <td>Zofia Schlachter</td></tr><tr class="data-row"> <td>Donnette Nichols</td></tr><tr class="data-row"> <td>Herta Hile</td></tr><tr class="data-row"> <td>Lurlene Pfeffer</td></tr><tr class="data-row"> <td>Teresita Wasson</td></tr><tr class="data-row"> <td>Milagros Copes</td></tr><tr class="data-row"> <td>Ai Stimac</td></tr><tr class="data-row"> <td>Brigida Rake</td></tr><tr class="data-row"> <td>Alida Paxton</td></tr><tr class="data-row"> <td>Juliann Mattingly</td></tr><tr class="data-row"> <td>Phil Cervantes</td></tr><tr class="data-row"> <td>Lauryn Salgado</td></tr><tr class="data-row"> <td>Glady Lavergne</td></tr><tr class="data-row"> <td>Shawna Koerber</td></tr><tr class="data-row"> <td>Alana Halloway</td></tr></table> </body> </html>

Using Firebase With Angular, Authentication, and MVC

26. July 2013 10:50 by admin in Angular, Firebase, Jquery
 

Firebase lets you create fully interactive apps with just frontend code. Stop thinking about servers and databases and focus on your application logic and your customers.

Apps built with Firebase respond immediately to data changes as they occur, bringing a whole new level of interactivity to your users.

Data stored in Firebase is directly accessible from the client. This means you can build dynamic, data-driven websites without worrying about servers or server code.

Firebase also supports authentication via a number of providers including Persona (BrowserID), Facebook, and Twitter.  Here is a demo “ToDo” MVC app using firebase as the back end.

First, the login page:

<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <title>Firebase Simple Login</title>
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/reset.css">
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/text.css">
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/960.css">
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/style.css">
  <script type="text/javascript" async="" src="js/ga.js"></script><script type="text/javascript" src="js/prettify.js"></script><style type="text/css">
                                                                                                                                                                                     </style>
</head>
<body onload="prettyPrint();">

  <div class="header">
    <div id=loggy class="ribbon"></div>
  </div>
&nbsp;<div class="container_12">

    <div class="grid_12">
      <br>
      <div class="box">
        &nbsp;</div>
    </div>

    <div class="clear"></div>
    <div class="grid_4">
      <br>
      <div class="box">
        <fieldset>
          <legend class="bold">Supported Providers</legend>
          <div class="content">
            <p>
              Click any of the links below to log in.
            </p>
            <div class="example facebook">
              <div class="icon"></div>
              <div class="description">
                <h4>Facebook</h4>
                <p><a href="javascript:login('facebook');">Log In »</a></p>
              </div>
            </div>
            <div class="example persona">
                <div class="icon">
                </div>
                <div class="description">
                    <h4>Persona</h4>
                    <p><a href="javascript:login('persona');">Log In »</a></p>
                </div>
            </div>
            <div class="example twitter">
              <div class="icon"></div>
              <div class="description">
                <h4>Twitter</h4>
                <p><a href="javascript:login('twitter');">Log In »</a></p>
              </div>
            </div>
            <div class="example password">
              <div class="description">
              </div>
            </div>
          </div>
        </fieldset>
      </div>
    </div>
    <div class="grid_8">
      <br>
      <div class="box">
        &nbsp;</div>

    </div>

    <div class="clear"></div>
    <div class="grid_12">
      <img src="js/hr.png">
    </div>

    <div id="contact">
      <div class="clear"></div>
      <div class="grid_4 prefix_4 suffix_4 center">
        <br>
      </div>

      <div class="clear"></div>
      <div class="grid_5 prefix_1 center">
      </div>
      <div class="grid_5 suffix_1 center">
      </div>
    </div>
  </div>

  <script type="text/javascript" src="js/firebase.js"></script>
  <script type="text/javascript" src="js/firebase-simple-login.js"></script>
  <script type="text/javascript" src="js/include.js"></script>
  <script type="text/javascript">
    var href = document.location.href;
    // FirebaseSimpleLogin demo instantiation
    var firebaseRef = new Firebase("https://peterbromberg.firebaseio.com");
    var auth = new FirebaseSimpleLogin(firebaseRef, function(error, user) {
      if (error) {
        // an error occurred while attempting login
        alert(error);
      } else if (user) {
        // user authenticated with Firebase, redirect to the app
        window.location.href='ToDo.html?id=' +user.id;

      // Log out so we can log in again with a different provider.
      // auth.logout();
      } else {
        // user is logged out
      }
    });
    function login(provider) {
      auth.login(provider);
    }

  </script>
<iframe style="display: none;"></iframe><iframe src="js/lp.htm" style="display: none;"></iframe></body></html>

 

I am showing the facebook, Twitter, and Persona login options. The live demo I’ll send you to at the end only has Persona enabled,

but it is a fully working app. What I do is after getting the user authenticated, I suffix the firebase endpoint with their User Id,

which is usually your email as the path. This ensures that each user has their own data store and cannot see others’.

Next is the ToDoctrl.js script, which loads in the todo.html page that we are redirected to from above:

/*global todomvc */
'use strict';

/**
* The main controller for the app. The controller:
* - retrieves and persist the model via the todoStorage service
* - exposes the model to the template and provides event handlers
*/
todomvc.controller('TodoCtrl', ['$scope', '$location', 'angularFire', 'filterFilter',
    function TodoCtrl($scope, $location, angularFire, filterFilter) {
        //  this is mine, suggest you get your own free firebase url here: https://www.firebase.com/pricing.html
        var url = "'https://peterbromberg.firebaseIO.com/todomvc" + getQueryVariable('id');
        url = url.replace(',', '');
        var promise = angularFire(url, $scope, 'todos');

        $scope.newTodo = '';
        $scope.editedTodo = null;

        if ($location.path() === '') {
            $location.path('/');
        }
        $scope.location = $location;

        promise.then(function(todos) {
            startWatch($scope, filterFilter);
        });
    }
]);

function startWatch($scope, filter) {
    $scope.$watch('todos', function () {
        $scope.remainingCount = filter($scope.todos, {completed: false}).length;
        $scope.completedCount = $scope.todos.length - $scope.remainingCount;
        $scope.allChecked = !$scope.remainingCount;
    }, true);

    $scope.$watch('location.path()', function (path) {
        $scope.statusFilter = (path === '/active') ?
            { completed: false } : (path === '/completed') ?
            { completed: true } : null;
    });

    $scope.addTodo = function () {
        if (!$scope.newTodo.length) {
            return;
        }

        $scope.todos.push({
            title: $scope.newTodo,
            completed: false
        });

        $scope.newTodo = '';
    };

    $scope.editTodo = function (todo) {
        $scope.editedTodo = todo;
    };

    $scope.doneEditing = function (todo) {
        $scope.editedTodo = null;
        if (!todo.title) {
            $scope.removeTodo(todo);
        }
    };

    $scope.removeTodo = function (todo) {
        $scope.todos.splice($scope.todos.indexOf(todo), 1);
    };

    $scope.clearCompletedTodos = function () {
        $scope.todos = $scope.todos.filter(function (val) {
            return !val.completed;
        });
    };

    $scope.markAll = function (completed) {
        $scope.todos.forEach(function (todo) {
            todo.completed = completed;
        });
    };
}

 

The rest is boilerplate Angular.js for the databinding. You can try out the demo here:

http://www.peterbromberg.net/firebase/index.htm

Be sure to login via Persona, as Facebook and Twitter authentication are not enabled on my demo. You can download a complete Visual Studio 2012 solution here:

FirebaseToDo.zip (263.07 kb)