Tag Archives: javascript

Insert Javascript code in JSF page

jsf_js
Usually you may need to insert a couple of JavaScript in your JSF page markup.
The following advice helps you do it right:

 <ui:composition ...>
    
    <ui:define name="body">
        
        <!-- your code -->
        
        <h:outputScript target="body">
            <![CDATA[
                alert("It works!");
            ]]>
        </h:outputScript>
        
        <!-- your code -->
        
    </ui:define>
    
</ui:composition>

So, as you see in JSF we use h:outputScript tag with CDATA inside to workaround issues like “The content of elements must consist of well-formed character data or markup” for valid XHTML.

Thanx to http://stackoverflow.com/a/4338816

Web

Check is jQuery loaded

jq
The simplest way to check jQuery library exists and loaded on page is next:

if (window.jQuery) {
  // your jQuery code here...
}

Thanx to http://stackoverflow.com/a/24284903

Web

Sticky header with CSS and JavaScript

Before scroll:
sticky_header1

After scroll:
sticky_header2

To obtain of sticky header effect you can use next code snippet.

1. Add CSS styles:

.persist_header_container {
}

.persist_header {
    padding: 10px;
    background: yellow;
    z-index: 1;
}

.floating_header {
    position: fixed;
    top: 0;
    visibility: hidden;
    -webkit-box-shadow: 0px 2px 12px 0px rgba(50, 50, 50, 1);
    -moz-box-shadow: 0px 2px 12px 0px rgba(50, 50, 50, 1);
    box-shadow: 0px 2px 12px 0px rgba(50, 50, 50, 1);
}

2. Add JS code:

$(function() {
    $(".persist_header_container").each(function () {
        var header = $(".persist_header", this);
        header.before(header.clone())
              .css("width", header.width())
              .addClass("floating_header");
    });

    window.updateHeader = function () {
        $(".persist_header_container").each(function () {
            $(".floating_header", this)
                .css({"visibility": ($(window).scrollTop() > $(this).offset().top ? "visible" : "hidden")});
        });
    };

    $(window).scroll(function () {
        updateHeader();
    });
    updateHeader();
});

Download source code: sticky_header

Also,
http://www.cssreset.com/creating-fixed-headers-with-css/
http://css-tricks.com/persistent-headers/

Web

OWL Carousel integration with AngularJS

owl
To up to work owl carousel (or other jQuery plugin) with AngularJS you need to perform some actions.
1. Download and include all plugin files:

<html>
<head>
    <link href="css/style.css" rel="stylesheet"/>
    <link href="vendor/owl-carousel/owl.carousel.css" rel="stylesheet"/>
    <link href="vendor/owl-carousel/owl.theme.css" rel="stylesheet"/>

    <script src="vendor/jquery.min.js"></script>
    <script src="vendor/owl-carousel/owl.carousel.js"></script>
</head>
<body>
    ...
</body>
</html>

2. Create directive in AngularJS:

app.directive('wrapOwlcarousel', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            var options = scope.$eval($(element).attr('data-options'));
            $(element).owlCarousel(options);
        }
    };
});

3. Place new tag in your page:

<wrap-owlcarousel class="owl-carousel" 
    data-options="{autoPlay: 5000, stopOnHover: true, 
        slideSpeed : 300, paginationSpeed : 400, singleItem : true}">
    <div>
        <img src="img/1.jpg"/>
    </div>
    <div>
        <img src="img/2.jpg"/>
    </div>
</wrap-owlcarousel>

See more about OWL Carousel.

Web

Application configuration in AngularJS

angcfg
If you are developing angular web-application, you ask how to involve configuration in it. I propose next pattern: create constant service and inject it in your other modules, services etc.
About constant in AngularJS.

1. Create app module as app.js file:

var app = angular.module('app', []);

2. Define constant service as config.js file:

app.constant('config', {
    apiUrl: 'http://localhost/api/v1',
});

3. Get your service with injected config as services.js file:

app.factory('userService', ['$http', 'config',
    function ($http, config) {
        return {
            register: function (email, password) {
                return $http({
                    url: config.apiUrl + '/user',
                    method: 'POST',
                    data: {
                        'Email': email,
                        'Password': password
                    }
                });
            },
            login: function (email, password) {
                return $http({
                    url: config.apiUrl + '/auth',
                    method: 'POST',
                    data: {
                        'Email': email,
                        'Password': password
                    }
                });
            },
            logout: function () {
                return $http({
                    url: config.apiUrl + '/auth',
                    method: 'DELETE'
                });
            },
            checkAuth: function () {
                return $http({
                    url: config.apiUrl + '/auth',
                    method: 'GET'
                });
            }
        };
}]);

So, config service is a singleton can be injected in any other services, modules etc.

Web

Get cursor position in textarea or input with JQuery

cursor_pos

The next snippet is a JQuery function helps to obtain the posiion of cursor in any HTML input element:

    (function($, undefined) {
        $.fn.getCursorPosition = function() {
            var el = $(this).get(0);
            var pos = 0;
            if ('selectionStart' in el) {
                pos = el.selectionStart;
            } else if ('selection' in document) {
                el.focus();
                var Sel = document.selection.createRange();
                var SelLength = document.selection.createRange().text.length;
                Sel.moveStart('character', -el.value.length);
                pos = Sel.text.length - SelLength;
            }
            return pos;
        }
    })(jQuery);

And here usage example:



getCursorPosition

As the result we’ll see next:
cursor_pos_result

The post was created by originally
http://stackoverflow.com/questions/1891444/how-can-i-get-cursor-position-in-a-textarea/1909997#1909997

Web

Overriding methods in Javascript

js_override
To override any method in JS+jQuery, use:

$(function(){
  SomeObject.prototype.someMethodName = function() {
    alert('Is overriden !!!');
  }
});

Ex is http://code.google.com/p/primefaces/issues/detail?id=4291
https://gist.github.com/sgruhier/1086231