Pages

Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Call API on click functions to update data

 


        var roleUpdate = document.querySelectorAll('.roleUpdate');


        for (var i = 0; i < roleUpdate.length; i++) {

            roleUpdate[i].addEventListener('click', function () {


                var permissionUserId = this.getAttribute('data-user-id');

                var permissionCodeId = this.getAttribute('data-role-code');


                const requestData = {

                    UserId: permissionUserId,

                    RoleId: permissionCodeId

                };


                //alert(JSON.stringify(requestData));


                fetch(`${window.location.origin}/api/users/updaterole`, {

                    method: 'POST',

                    headers: {

                        'Content-Type': 'application/json'

                    },

                    body: JSON.stringify(requestData)

                })

                    .then((response) => {

                        if (response.ok) {

                            return response.json();

                        } else {

                            throw new Error(`Error: ${response.status}`);

                        }

                    })

                    .then((data) => {

                        toastr.success('Update User Roles Success');

                        // alert(data.msg);

                    })

                    .catch((error) => {

                        // alert(error.message);

                        toastr.error('Update Failed');

                    });



            });

        }



        // User Active Inactive status update


        var userStatus = document.getElementById("userStatus");



        userStatus.addEventListener('click', function () {


            var puserStatusId = this.getAttribute('data-user-id');


            alert(puserStatusId);


                const requestData = {

                UserId: puserStatusId,

                };


                //alert(JSON.stringify(requestData));


                fetch(`${window.location.origin}/api/users/updaterole`, {

                    method: 'POST',

                    headers: {

                        'Content-Type': 'application/json'

                    },

                    body: JSON.stringify(requestData)

                })

                    .then((response) => {

                        if (response.ok) {

                            return response.json();

                        } else {

                            throw new Error(`Error: ${response.status}`);

                        }

                    })

                    .then((data) => {

                        toastr.success('Update User Status Success');

                        // alert(data.msg);

                    })

                    .catch((error) => {

                        // alert(error.message);

                        toastr.error('Update Failed');

                    });



            });


on button click add text boxes and delete script

  <button onclick="addField()" class="btn btn-outline-primary mb-3 btn-sm" type="button">+ Add Field</button>


                        <div id="fieldSection" class="mb-3"></div>


let fieldCount = 0;


function addField() {

    fieldCount++;


    const textboxName = `newfield_${fieldCount}`;


    const textbox = document.createElement("input");

    textbox.type = "text";

    textbox.name = textboxName;

    textbox.classList.add("form-control", "mb-2");


    // Remove button


    const removeBtn = document.createElement("button");

    removeBtn.textContent = "X";

    removeBtn.classList.add("btn", "btn-sm", "btn-outline-danger");

    removeBtn.addEventListener("click", () => {

        removeField(textboxName);

    });


    const fieldContainer = document.createElement("div");

    fieldContainer.classList.add("fieldContainer");

    fieldContainer.appendChild(textbox);

    fieldContainer.appendChild(removeBtn);


    const fieldSection = document.getElementById("fieldSection");

    fieldSection.appendChild(fieldContainer);

}


function removeField(textboxName) {

    const removable = document.querySelector(`input[name="${textboxName}"]`).parentNode;


    const fieldSection = document.getElementById("fieldSection");

    fieldSection.removeChild(removable);

}

Active class to current page link

To highlight the current page add an active or another class name to the link when the linked page is opened using java script.



  <script>
$(".navbar-nav a").filter(function(){
    return this.href == location.href.replace(/#.*/, "");
}).addClass("active");
  </script>

Fix JQuery Plugin issue in Asp.net Update Panel

When you are using asp.net and using Jquery plugins JQuery UI Sliders these Jquery controls and scripts are not working in Update panel after a form submit postbacks.

Solution : document ready will fire only once, not during partial postbacks. You need to call some functions after each partial post back is happend

<script type="text/javascript">
    Sys.Application.add_load(function() {<!--JQUERY CODE GOES HERE-->});
</script> 

Responsive image link map

This is a Copy and Paste Quick fix solution for HTML Image Map linking for responsive design with Javascript and Jquery. Add this code before closing your body tag.



<img src="images/worldmap-world-map.jpg"   usemap="#image-map">
       
       
<map name="image-map">
    <area target="" alt="North America/Canada" title="North America/Canada" href="#" coords="373,217,393,255,405,272,405,312,391,373,354,368,352,415,371,443,344,473,290,496,213,446,168,395,155,354,137,312,114,293,87,291,45,315,41,276,30,240,18,216,27,185,35,156,59,146,116,153,128,177,155,161,169,152,178,108,260,110,283,70,313,66,344,76,336,143,323,175,376,233,404,277,369,262" shape="poly">
    <area target="" alt="Sri Lanka" title="Sri Lanka" href="#" coords="931,505,892,460" shape="rect">
    <area target="" alt="Europe" title="Europe" href="#" coords="606,362,633,369,654,385,670,371,679,395,707,404,747,364,777,354,776,269,756,270,753,229,732,224,726,205,707,205,706,158,684,158,624,224,617,248,575,225,536,226,534,244,574,255,601,254,584,265,565,279,574,306,564,327,543,335,546,370,575,384,611,379" shape="poly">
    <area target="" alt="Australia" title="Australia" href="#" coords="1011,611,1035,588,1056,575,1079,570,1088,550,1122,551,1134,574,1150,575,1149,532,1168,537,1180,574,1189,582,1197,598,1195,639,1175,650,1176,667,1156,671,1151,691,1111,696,1097,658,1075,650,1067,663,1048,675,1009,660" shape="poly">
    <area target="" alt="East Asia" title="East Asia" href="#" coords="948,405,966,399,975,358,1051,357,1067,335,1089,333,1102,340,1109,362,1125,383,1124,405,1068,407,1067,431,1058,451,1023,470,1034,487,1068,474,1088,493,1073,523,1050,549,1013,558,992,519,971,489,959,451,962,436" shape="poly">
</map>



!function(){"use strict";function a(){function a(){function a(a,d){function e(a){var d=1===(f=1-f)?"width":"height";return c[d]+Math.floor(Number(a)*b[d])}var f=0;j[d].coords=a.split(",").map(e).join(",")}var b={width:l.width/l.naturalWidth,height:l.height/l.naturalHeight},c={width:parseInt(window.getComputedStyle(l,null).getPropertyValue("padding-left"),10),height:parseInt(window.getComputedStyle(l,null).getPropertyValue("padding-top"),10)};k.forEach(a)}function b(a){return a.coords.replace(/ *, */g,",").replace(/ +/g,",")}function c(){clearTimeout(m),m=setTimeout(a,250)}function d(){l.width===l.naturalWidth&&l.height===l.naturalHeight||a()}function e(){l.addEventListener("load",a,!1),window.addEventListener("focus",a,!1),window.addEventListener("resize",c,!1),window.addEventListener("readystatechange",a,!1),document.addEventListener("fullscreenchange",a,!1)}function f(){return"function"==typeof i._resize}function g(a){return document.querySelector('img[usemap="'+a+'"]')}function h(){j=i.getElementsByTagName("area"),k=Array.prototype.map.call(j,b),l=g("#"+i.name)||g(i.name),i._resize=a}var i=this,j=null,k=null,l=null,m=null;f()?i._resize():(h(),e(),d())}function b(){function b(a){if(!a.tagName)throw new TypeError("Object is not a valid DOM element");if("MAP"!==a.tagName.toUpperCase())throw new TypeError("Expected <MAP> tag, found <"+a.tagName+">.")}function c(c){c&&(b(c),a.call(c),d.push(c))}var d;return function(a){switch(d=[],typeof a){case"undefined":case"string":Array.prototype.forEach.call(document.querySelectorAll(a||"map"),c);break;case"object":c(a);break;default:throw new TypeError("Unexpected data type ("+typeof a+").")}return d}}"function"==typeof define&&define.amd?define([],b):"object"==typeof module&&"object"==typeof module.exports?module.exports=b():window.imageMapResize=b(),"jQuery"in window&&(jQuery.fn.imageMapResize=function(){return this.filter("map").each(a).end()})}();
//# sourceMappingURL=imageMapResizer.map
jQuery('map').imageMapResize();
//Calling with Jquery

Link to send a text message in html - Cross Browser Solution

Cross-Browser Solution for Creating a sms link in html web page to click and send sms from your smart phone with a message and a number. This will work in web browsers for iOS 5,6,7,8,9,10 and Android versions.

function checkMobileOS() {
 
    var MobileUserAgent = navigator.userAgent || navigator.vendor || window.opera;
 
    if (MobileUserAgent.match(/iPad/i) || MobileUserAgent.match(/iPhone/i) || MobileUserAgent.match(/iPod/i)) {
 
        return 'iOS';
 
    } else if (MobileUserAgent.match(/Android/i)) {
 
        return 'Android';
 
    } else {
 
return 'unknown';
 
    }
 
}
 
var message_text = 'Some message goes here';
 
var href = '';
 
if (checkMobileOS() == 'iOS') {
 
    href = "sms:+123456789&body=" + encodeURI(message_text);
 
}
 
if (checkMobileOS() == 'Android') {
 
    href = "sms:+123456789?body=" + encodeURI(message_text);
 
}
 
document.getElementById("sms_link").setAttribute('href', href);


<a id="sms_link" href="#">Tap to SMS</a>

Bootstrap modal popup automatically timeout close

bootstrap modal popup automatically timeout close

<script>
        $(document).ready(function () {

            $('.face').click(function () {
                $('#myModal').modal('show', function () {
                    clearTimeout(myModalTimeout);
                });

                myModalTimeout = setTimeout(function () {
                    $('#myModal').modal('hide');
                }, 1000);

            });

        });
</script>

Using Google No captcha Re captcha in your web page 2016

<?php

if(isset($_POST['submit']))
{
$secret = "XXXXXXXXXXXXXXXXXXXXX"; //secret key

$response = $_POST['g-recaptcha-response']; // captcha response

$remoteip = $_SERVER['REMOTE_ADDR']; // get user ip

$url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip"); // pass values to recapcha API

$result = json_decode($url, TRUE);

if($result['success']==1)
{
echo "SUCCESS"
}
else{
echo "failed"
}

}

bootstrap change active tab on page reload

  <script>
  $('.nav-tabs-custom a').click(function(e) {
  e.preventDefault();
  $(this).tab('show');
});

// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
  var id = $(e.target).attr("href").substr(1);
  window.location.hash = id;
});

// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('.nav-tabs-custom a[href="' + hash + '"]').tab('show');
  </script>

slick slider horizontal scroll with mouse wheel js

<script src="js/mousewheel.js"></script>
<script src="slick/slick.min.js" type="text/javascript"></script>
        <script>
            $('.slickc').slick({
            })
                    .on("mousewheel", function (event) {
                        event.preventDefault();
                        if (event.deltaX > 0 || event.deltaY < 0) {
                            $(this).slick("slickNext");
                        } else if (event.deltaX < 0 || event.deltaY > 0) {
                            $(this).slick("slickPrev");
                        }
                    });
        </script>

Using Waypoints js on a web page - example

<script>

    var $imga = $('#mimg');

    $imga.waypoint(function (direction) {
        if (direction === 'down') {



            $('#mimg').removeClass('animated bounceOutRight');
            $('#mimg').addClass('animated fadeIn');

            $('.banny').removeClass('animated bounceOutLeft');
            $('.banny').addClass('animated fadeIn');

//            $('.ptextxs').textillate({
//                in: {effect: 'fadeInDown'}
//            });

        }
        else {
            $('#mimg').removeClass('animated  fadeIn');
            $('#mimg').addClass('animated bounceOutRight');


            $('.banny').removeClass('animated fadeIn');
            $('.banny').addClass('animated bounceOutLeft');
        }
    },
            {offset: '65%'});







</script>

Animate / function before go to the next page on link click - Jquery

Animate / function before go to the next page on link click - Jquery

<script>
    $(".mlink").click(function (e) {
        
        e.preventDefault();
        
        var link = $(this).attr('href');
        
        $('body').addClass('animated hinge').delay(3000).queue(function(){
            
//.delay(3000).queue - to delay next function

           location.href = link;            
          
        });
        });
</script>

or

<script>
$("#info-text-container").click(function(){
    setTimeout(function(){
       $("#info-text").addClass("info-text-active");
   }, 500);

});
</script>

Pure CSS3 JavaScript Pre loader without JQuery

Simple JavaScript pre-loader which works without the JQuery library created with CSS3 and JS.


<div id="spinner"> </div>

#spinner {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 999999999;
background: rgba(255,255,255,0.95);

}


<script type='text/javascript'>
  
  function attach(element,listener,ev,tf){

if(element.attachEvent) {

    element.attachEvent("on"+listener,ev);

}else{

    element.addEventListener(listener,ev,tf);

}

}

function fadeOut(element,startLevel,endLevel,duration,callback){

var fOInt;

    op = startLevel;

fOInt = setInterval(function() {

    if(op<=endLevel){

    element.style.opacity = endLevel;
    element.style.filter = "alpha(opacity = " + endLevel + ")";

    clearInterval(fOInt);

        if(typeof callback == 'function') callback(true);

    }else{

    op -= 0.1;

    element.style.opacity = op;
    element.style.filter = "alpha(opacity = " + op*100 + ")";

    }

    },duration);

}

attach(window,'load',function(){
    fadeOut(document.getElementById('spinner'),1,0,50,function(cb){
        
        document.getElementById("spinner").style.display = "none";

    //alert('The loader has faded out!')

    });
    
},false);
  
</script>

Print only a div in web page No CSS JS Only

Printing only a specific div in a web page using javascript with a print button




<script>
function printContent(el){
var restorepage = document.body.innerHTML;
var printcontent = document.getElementById(el).innerHTML;
document.body.innerHTML = printcontent;
window.print();
document.body.innerHTML = restorepage;
}
</script>


<button class="btn btn-info" onclick="printContent('print')"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> Print Content</button>

<div class="col-lg-12" id="print">
This content will be printed
</div>

Search This Blog