Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Thursday, April 25, 2024

Html JS - Handle Browser Back Button on SPA

In Single page applications, we will not have dedicated URLs. So on click of Browser Back button it will navigate us to previous page and we lost our current page changes. We can handle this with native JavaScript functions,

Create Html Page as below to mimic SPA, 


On click of each Page button, it can switch the content,




On Each Page navigation we can set the hash URL something like below using history.pushstate or location.hash



Now on click of back button use the hashchange event to detect and open the page accordingly


Here is full code:

<html>

<head>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>

</head>

<body>

    <input type="button" value="Page1" onclick="openPage('1');" />

    <input type="button" value="Page2" onclick="openPage('2');" />

    <input type="button" value="Page3" onclick="openPage('3');" />

 

    <div id="page1" class="page">Page 1 Content</div>

    <div id="page2" class="page">Page 2 Content</div>

    <div id="page3" class="page">Page 3 Content</div>

 

 

    <div id="history"></div>

</body>

 

<script>

    $(document).ready(function () {

        hideAllPages();

     });

 

    $(window).on('popstate', (e) => {

        e.preventDefault();

        var currentLocation = window.location.pathname;

        history.push(currentLocation)

    });

     window.onbeforeunload = function () {

        return "Are you sure you want to leave this page?";

     };

    addEventListener("hashchange", (event) => {

        alert("New" + event.newURL);

        alert("Old" + event.oldURL);

        var currentHash = event.currentTarget.location.hash;

        openPage(currentHash.replace("#", ""), true);

     });

    function hideAllPages() {

        $(".page").hide();

    }

    function openPage(pageId, ignoreHistoryPush = false) {

        hideAllPages();

        $("#page" + pageId).show();

        if (!ignoreHistoryPush)  //This is to not add history on everytime

            history.pushState({ page: pageId }, pageId, '#' + pageId);
            //
location.hash = pageId  //This way also can set it

    }

 

 

</script>

</html>


Wednesday, December 6, 2023

Html - Render Html Dynamically into Frame without Hosting and Communicate from Parent

 In case we want to render Html dynamically into website as frame without hosting the Html into another website, we can use of this code Blob with createObjectURL to render dynamically,


Create Parent Website as below:

<html>

<head>

<script>

// This function will update the iframe src with the HTML code from the textarea

function renderHTML() {

   // Get the textarea element by its id

  var textarea = document.getElementById("html-code");

  // Get the iframe element by its id

  var iframe = document.getElementById("html-frame");

  // Create a blob object from the textarea value

  var blob = new Blob([textarea.value], {type: "text/html"});

  // Create a URL object from the blob object

  var url = URL.createObjectURL(blob);

  // Set the iframe src to the URL object

  iframe.src = url;

}

 

function postIframe(){

 var iframe = document.getElementById("html-frame");

 iframe.contentWindow.postMessage("Hi, Message From Parent Website", '*');

}

  </script>

</head>

<body>

  <h1>HTML Editor</h1>

  <p>Enter some HTML code in the textarea below and click the button to render it in the iframe.</p>

<textarea id="html-code" rows="10" cols="50">

        <h2>Hello World</h2>

        <p>This is a simple HTML document.</p>

</textarea>


<br>

<button onclick="renderHTML()">Render HTML</button>

<br>

<iframe id="html-frame" width="500" height="300"></iframe>

<br />

<button onclick="postIframe()">Post Iframe</button>

</body>

</html>


In case we want to communicate with iFrame, we can use of postMessage, for that we can add the following code into Html of iFrame

iFrame Html Content as below:


<!DOCTYPE html>

<html>

<head>

  <title>Page Title</title>

</head>

<body>

  <h1>This is a Heading</h1>

  <p>This is a paragraph.</p>

  <script type="text/javaScript">

     function addListener() {

       window.addEventListener('message', event => {

        // IMPORTANT: check the origin of the data!

        //if (event.origin === 'https://your-parent-site-url') {

        // The data was sent from your site.

        // Data sent with postMessage is stored in event.data:

        alert(event.data);

        //} else {

        // The data was NOT sent from your site!

        // Be careful! Do not use it. This else branch is

        // here just for clarity, you usually shouldn't need it.

        return;

        //}

      });

     }

    addListener();

   </script>

<div> Footer Content</div>

</body>

</html>

Tuesday, March 7, 2017

JavaScript - Simple Export to excel

To export excel in JavaScript without any server side techiques, we can use following steps

Used blob file saver for download https://github.com/eligrey/FileSaver.js

Step 1: Create Html Content with required styles as below

var tableHtml = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
        tableHtml += '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets>';
        tableHtml += '<x:ExcelWorksheet><x:Name>PlanFundLineup</x:Name>';
        tableHtml += '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
        tableHtml += '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
  tableHtml += "<div><table  border='1'>" +
        tableHtml += "<thead>" +
        tableHtml += "<tr><th>" +
        tableHtml += "Header Text" +
        tableHtml += "</th></tr>" +
 tableHtml += "</thead>" +
               "<tbody>" +
        tableHtml += "<tr><td>" +
        tableHtml += "Content Text" +
        tableHtml += "</td></tr>" +
               "</tbody>" +
              "</table></div>";
        tableHtml += '</body></html>';

Step 2: Download this html content using blob

var blob = new Blob([tableHtml], { type: "application/vnd.ms-excel;charset=utf-8" })
window.saveAs(blob, "excelname.xls");


Tuesday, June 28, 2016

AngularJS - BootStrap Popover Directive

In some cases we need to show some popover as tooltip or as dialog

Here am going to use BootStrap Popover, this plugin is part of BootStrap.js file or we can include spearately. For more information about that read here 

I am going to create simple popover

Step 1; Create your html pages, include BootStrap js files, AngularJS, JQuery basic setups

Step 2: Here is what I created directive to make PopOver work with AngularJS, add this directive to your application

var app = angular.module('appModuleName');

app.directive('popover', ['$compile',function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            $(element).popover({
                html: true,
                title:  attrs.popoverTitle || "Header",
                content: function () {
                    return $compile($("#" + attrs.popoverContent).html())(scope);
                },
                placement: attrs.popoverPlacement || "top"
            });
        }
    };

}]);


Step 3: In your HTML, just use this directive and pass attributes

<input type="button" popover popover-title="Header Text" popover-content="popover-content-id" popover-placement="top"/>

Step 4: Here you can pass your Title, ContentId, placement (Top, Bottom, Right, Left) etc.  This popover-content-id is div with contents

  <div id="popover-content-id" class="hide">
Some content here..
  </div>