Open window with information (AJAX WAY)

In this example we will execute AJAX that will return data which will be visualised in new window (tab).

$(document).on("click", ".sysnav", function(){ //On clicked button
    id=$(this).attr('id');                 //Command that will be executed in script.php
        $.ajax({
              url:'script.php',
              type:'POST',
              data:{ 
                command:id 
              }  
        }).done(function(data){
            var target = window.open("/admin.php");   //Open new window
            target.NavigationPopup = data;            //Data to be loaded in new window
        });     
});

Div with class “content” in new window will be filled with data from AJAX.
File “admin.php”(new window) must include this code.

var NavigationPopup;            //Data from ajax

$(document).ready(function(){
    if(NavigationPopup){    $('.content').html(NavigationPopup);    } //Fill the "content" div
}

Load jQuery if not loaded (Asynchronous Way)

If you load scripts through ajax and they won’t execute.

<script>
// Only do anything if jQuery isn't defined
if (typeof jQuery == 'undefined') {

    if (typeof $ == 'function') {
        // warning, global var
        thisPageUsingOtherJSLibrary = true;
    }
    
    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://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', function() {
    
        if (typeof jQuery=='undefined') {       
            // Super failsafe - still somehow failed...     
        } else {        
            // jQuery loaded! Make sure to use .noConflict just in case
            
            // HERE IS THE CODE WE WANT TO EXECUTE ASYNC
            $.getScript( "js/calculations_reg.js", function( data, textStatus, jqxhr ) {
              // console.log( data ); // Data returned
              // console.log( textStatus ); // Success
              // console.log( jqxhr.status ); // 200
              // console.log( "Load was performed." );
            });
            //nik fancyCode();          
            //nik if (thisPageUsingOtherJSLibrary) {
                // Run your jQuery Code
            //nik } else {
                // Use .noConflict(), then run your jQuery Code
            //nik }     
        }   
    }); 
} else { // jQuery was already loaded
    // Run your jQuery Code
};
</script>

After that place your code that you want to run.

Pagination example

PHP and HTML

<ul class="pagination">
    <li><a href="javascript:void(0);" class="pbutton"></a></li>
<?php 
        if(!empty($_POST['selected'])){$page = $_POST['selected'];}else{$page=1;} //selected page
    $last=6; //number of pages ( total number of articles / number of shown articles on page )
    $top = $page+2; 
    $bottom = $page-2;
    for($x=$bottom;$x<$top;$x++){
        if($top>$last){$top=$last;}
        if($x<=0){$bottom+=1;$top+=1;}                              
    }
                
    for($i=$bottom;$i<=$top;$i++){ ?>
           <li class="<?php echo ($page==$i)?"active":"";?>"><a href="javascript:void(0);" class="pbutton"><?=$i;?></a></li>
<?php 
    }
                        
    if($page!=$last){ ?>
        <li><a href="javascript:void(0);" class="pbutton last_page" id="<?=$last?>" ></a></li>
    <?php } ?>
                            
</ul>

jQuery

$(document).on("click",".pbutton",function() {
        var selected = this.text; //Selected page
        if(selected==""){selected = 1;} //first rows
        if(selected==""){selected = $(".last_page").attr("id");} //last rows
        
        $.ajax({
          url:'admin.php',
          type:'POST',
          data:{ 
            command:"show_regular_quotation", //name of var: value of var  
            selected:selected
          }  
         }).done(function(data){
            $(".content").html(data);
        });     
    });

The code is perfectly compatible with bootstrap.

Display A Popup Only Once Per User

HTML:

<div id="wrap-banner">
        <div id="banner">
        <div class="text">    <br>   
        <br>
        <a href="" target="_blank"><span style="height: 80px;background: #161616;padding: 20px 50px;color:#fff;background-color:#4865a1;"><strong>JOIN US</strong></span></a>
        </div>
        <span id="close-offer"><img src="/images/cnew/close-banner.png" /></span>
        </div>
    </div>

jQuery code:

jQuery(document).ready(function(){
        
        if(localStorage.getItem('popState') != 'shown'){
            jQuery('#wrap-banner').css({
                'display':'block'
            });
            localStorage.setItem('popState','shown')
        }   
        
        jQuery('#close-offer').click(function(){
            jQuery('#wrap-banner').hide();
        });
    });

Simple jQuery image/banner changer

This is simple image slider that change images/banners with fade effect in declared interval.

HTML:

<div class="swrapper">
    <div id="slider">
         <a href="#" target="_blank"><img id="1" src="baner_new_site_bg.png"/></a>
         <a href="#" target="_blank"><img id="2" src="banner.png"/></a>
    </div>
</div>

Continue reading “Simple jQuery image/banner changer”

How to create simple parallax effect.

It is really simple to create parallax effect on your site. Add this script to your html head.

<script>        
    function onLoad() {
        window.onscroll = function() {
            var speed = 4.0;
            document.body.style.backgroundPosition = "center " + Math.round(-window.pageYOffset / speed) + "px";
        }
    }   
</script>

In your body tag add -> onload=”onLoad()”. This will automatically start the script on page load. Here is some css you will need for example to work:

body{background: url("/image/bg-texture-1200.png") repeat-x top center; width: 100%;  background-color: #E9F5FA; background-attachment: fixed;}

Passing values in JS in objects is by reference

Passing in a primitive type variable like a string or a number, the value is passed in by value. Passing in an object, however, passes it in by reference.

Here is an example:

<script>
function printStudent(student){
    for(var i in student.marks){
        console.log(marks[i].subject+" s ocentka "+marks[i].score);
    }
}
var marks=[ {subject:"OOP",score:'6'} ];
var student = {name:"Dido",marks:marks};
printStudent(student);
marks[0].score=5;
printStudent(student);
</script>

What is this (IIFE) construct in javascript?

Immediately-Invoked Function Expression, or shorter: IIFE. It executes immediately after it’s created.
This pattern is often used when trying to avoid polluting the global namespace, because all the variables used in the function are not visible outside its scope. It’s good to use when we have multiple functions with the same name.

<script>
//IIFE Immediately-Invoked Function Expression
var b = ( function(){
        function a(){return 5;}
        return a();
}());   
</script>

<script>
    function a(){return 4;}

console.log(b);
</script>

The output will be 5.