Category - Frontend-Technology

Web Components: The Future of Modular UI Design
Jul 26, 2024

Have you ever wanted to create reusable JavaScript building blocks that work in any project, no matter what framework others are using? If so, then Web Components might be the solution you're looking for! This Guide is intended to dive into custom components. Web Components are a collection of tools that expand the web platform. This allows you to define new HTML elements with specific functionality and behavior. There’s a lot to think about, and writing a component can require a lot of boilerplate code. Fortunately, some great libraries can make creating custom elements more straightforward, and save you a lot of time and effort. However, if you’re writing lots and lots of custom elements, using a library can make your code simpler and cleaner, and your workflow more efficient. What are the Web Components? That allows developers to create custom, reusable, encapsulated HTML elements. Custom Elements: Enables the creation of new HTML tags. Shadow DOM: Provides encapsulation for custom elements, ensuring that their internal structure and styles do not interfere with the rest of the document. HTML Templates: Allows the definition of HTML templates that can be reused and instantiated in custom elements. Note: The name of a Web Component needs to contain a dash (-). This naming convention is put into place to enable the HTML parser to distinguish custom from regular elements and also avoid creating your own components that could be added as part of future HTML standards. <mycard></mycard>, <card></card> or <CardComponent></CardComponent> are all invalid names, while <my-card></my-card> is allowed.   Why Web Components? Web components allow us to take our frontend widgets off this cycle of getting rebuilt in the newest framework flavor Reuse is King: Ever build the same button style ten times? With Web Components, you define a button component once and use it everywhere! Framework Freedom: No more framework lock-in! Web Components work seamlessly with vanilla JavaScript, React, Angular, or any framework you choose. Encapsulation Power: Components keep their styles and functionality isolated, preventing conflicts and promoting cleaner code. To define a new custom element using the v1 implementation, you simply create a new class that extends HTMLElement using ES6 syntax and register it with the browser:   class MyElement extends HTMLElement {...} window.customElements.define('my-element, MyElement); //example usage in your app: <my-element></my-element> NOTE: Only Chrome V67 and up supports customized built-in elements! Let's Jump over the example, Building with LitElement. Certainly! Below is an example of a toggle switch web component using Lit. This example includes the essential parts: defining the component, its styles, and its template. Code Snippets for User Template:   // component's template render() { return html` <label class="switch"> <input type="checkbox" .checked="${this.checked}" @change="${this._toggle}"> <span class="slider"></span> </label> `; } // Method handler. // The toggle handler public _toggle(event): void { this.checked = event.target.checked; this.dispatchEvent(new CustomEvent('toggle', { detail: this.checked })); } Explanation: We import LitElement and the html function for templating. We define a AppToggle class that extends LitElement. We set the name property to accept a string value. The render method defines how the component looks using LitElement's HTML-like syntax. Finally, we register the app-toggle custom element.   Now, you can use your app-toggle component anywhere in your HTML: <div style="display: block; padding:200px"> <app-toggle name="toggle" checked="true"></app-toggle> <app-toggle name="World"></app-toggle> </div> The Future is Modular! Web Components offer a powerful and versatile approach to building user interfaces. With Reusability, framework independence, and clear separation of concerns, they are poised to be a significant force in the future of web development. So, start building your UI block party with Web Components today! I have included a screenshot below from WebComponents.org that shows the current browser support - a really nice community guide worth checking out and adding to your Bookmarks: Conclusion In this article, you took your first step into the world of web components. Web components have no third-party dependencies, so using them won't have a big impact on your bundle size. But for more complex components, you may want to reach for a library like Svelte or Lit.    

Setup Firebase account with React App
Feb 23, 2024

Establishing your account on Firebase and connecting it with your React APP encompasses multiple steps, such as initiating a Firebase project, adjusting your project settings, and acquiring your Firebase configuration details. Below is a comprehensive, step-by-step guide:    Step 1: Go to the Firebase Console  From this link, you can go to the Firebase console app  https://console.firebase.google.com/    Step 2: Sign in or create a Google Account  If you have a Google account you can directly sign in and  if you don’t have then you need to create one to sign in    Step 3: Create a new Firebase Project  Click on the Create a Project button.       Enter a Project name.          And Click on the Continue button.  Enable Google Analytics (Optional)          From here you can enable or disable the Google Analytics option. It is recommended to enable Google Analytics for better insights.  Once you click on the Continue button, firebase will set your project and redirect you to the Project dashboard.           Add an app to your project:  Click on the Project Settings button and from there you can see the configuration of your project.           Choose the platform for your app (iOS, Android, or Web).                 Enter an app nickname (optional) and click on Register app.          Obtain Firebase configuration details.    For a web app, Firebase will provide you with a configuration object containing keys like apiKey, authDomain, projectId, etc. Copy this information as you'll need it in your application.  Step 4: Create database  For Creating the database, go to the build option and click on the “FireStore Database” option     Once you navigate to Firestore Database, click on “Create database” button.    Step 5: Install the Firebase Package  After creating your React app, change directory to your project's root folder and install the Firebase package by running:  npm install firebase    Step 6: Initialize Firebase in your React APP  Create a new folder inside your project src directory. You can call this firebase_setup. Next, create a firebase.js file inside that folder. Then paste the code generated earlier into this file. Thus, you can fine-tune the generated code as follows: import { initializeApp } from "firebase/app";  import { getFirestore } from "@firebase/firestore"    const firebaseConfig = {  apiKey: process.env.REACT_APP_apiKey,  authDomain: process.env.REACT_APP_authDomain,  projectId: process.env.REACT_APP_projectId,  storageBucket: process.env.REACT_APP_storageBucket,  messagingSenderId: process.env.REACT_APP_messagingSenderId,  appId: process.env.REACT_APP_appId,  measurementId: process.env.REACT_APP_measurementId  };    const app = initializeApp(firebaseConfig);  export const firestore = getFirestore(app)    Step 7: Test Your Firebase Connection  You can test the connection by submitting dummy data to Firestore. Start by creating a handles folder inside your project's src directory. Create a submit handler inside this file. You can call this handlesubmit.js, for instance:  import { doc, setDoc } from "@firebase/firestore"  import { firestore } from "../firebase_setup/firebase"  const handleSubmit = async(testdata) => {  const handleSubmit = async(employeeData) => { try { const employeeDocRef = doc(firestore, 'EmployeeDb', 'Employee_tbl'); await setDoc(employeeDocRef, employeeData); console.log("Added employee data successfully"); } catch(e) { console.error("Error adding data employee", e); } } export default handleSubmit  //Then inside App.js:  import './App.css';  import handleSubmit from "./handler/handlesubmit.js"; import { useState} from 'react';  function App() {  const [employee, setEmployee] = useState({ name: "", age: "", position: "", }); // Function to handle input changes const handleChange = (e) => { const { name, value } = e.target; setEmployee({ ...employee, [name]: value }); }; const submithandler = (e) => { e.preventDefault(); handleSubmit(employee); };   return ( <> <div className="form-container" onSubmit={submithandler}> <form action="#" > <div className="form-group"> <label >Employee Data:</label> <input type="text" name="name" placeholder="Name" value={employee.name} onChange={handleChange} /> <input type="text" name="age" placeholder="Age" value={employee.age} onChange={handleChange} /> <input type="text" name="position" placeholder="Position" value={employee.position} onChange={handleChange} /> <input type="submit" value="Submit" /> </div> </form> </div> </> ); }    export default App;    Run your React app and try submitting data via the form. Refresh the Firebase database console to see the submitted information in your collection.  When you run your React app it will look like this. Here when you add all the details of the employee and click on the Submit button Whatever you entered in the form it will be reflected in your Firestore database. Fantastic! You have effectively established your Firebase account and configured it in your react application.  

The Ultimate Angular vs React Comparison
Feb 08, 2024

Overview  In the ever-evolving landscape of web development, the choice of a JavaScript framework can be akin to selecting the right tool for a complex job. Among the myriad options available, two stalwarts, Angular and React, have risen to prominence, captivating the developer community with their unique approaches to building modern, dynamic user interfaces. By examining factors such as performance, learning curve, and project requirements, we aim to equip you with the insights needed to crack the JavaScript conundrum and make an informed choice for your next project.    What is Angular?  Angular is an open-source JavaScript framework written in TypeScript maintained by Google and its primary purpose is to develop single-page applications. It provides a collection of well-integrated libraries that cover a wide variety of features, including routing, forms management, client-server communication, and more. You can write, compile, test, and update your code with the aid of its development tools.    Key features and concepts of Angular include:  Cross-Platform  Component-Based Architecture  Dependency Injection  Directives  RxJS (Reactive Extensions for JavaScript)  Two-way Data Binding    Advantages of Angular Angular promotes a modular architecture, allowing developers to organize code into separate and reusable modules.  Angular extends HTML syntax. With directives.  Angular uses two-way data binding, meaning that the model state changes automatically whenever any interface element changes.  Angular uses a powerful dependency injection system, making it easier to manage and test components.  Angular is built using TypeScript, a statically typed superset of JavaScript. TypeScript adds static typing, interfaces, and other features that enhance code quality, readability, and maintainability.  Angular provides a powerful CLI that streamlines common development tasks.    What is React?  React is a JavaScript-based UI development library that aims to simplify the intricate process of building interactive user interfaces. It is primarily used for building user interfaces (UIs) for single-page applications where the user interface needs to be dynamic and highly responsive. Developed and maintained by Facebook, React has gained widespread adoption in the web development community due to its declarative and efficient approach to building UI components.   Key features and concepts of React include:  Virtual DOM  JSX Syntax  Component based architecture  Declarative Syntax  Props  Hooks    Advantages of React React uses a virtual DOM to optimize rendering performance. Updates to a virtual version of the DOM are triggered by changes in the UI, and React determines the most effective way to update the real DOM to minimize needless re-renders. It has faster updates with both server-side and front-end support.  Easier debugging with declarative views.  React.js promotes the concept of reusable components, which are self-contained modules that can be used across different parts of an application.  React.js has a large and active community of developers who constantly contribute to its growth and improvement.  React.js is highly scalable and flexible, making it suitable for building applications of any size or complexity.    Quick comparison between Angular and React      Angular vs. React: When to choose which?     Angular or React which is best?  Ultimately, the choice between Angular and React is subjective and depends on the specific needs of your project and your team's preferences and expertise. It's also worth noting that both Angular and React have been widely adopted in the industry and have proven successful in building modern and scalable web applications. 

Mastering jQuery: Simple Tricks for Success
Aug 10, 2020

1. Back to top button $('a.top').click(function() { $(document.body).animate({scrollTop : 0},800); return false; }); //Create an anchor tag <a class=”top” href=”#”>Back to top</a> As you can see using the animate and scrollTop functions in jQuery we don’t need a plugin to create a simple scroll to top animation. By changing the scrollTop value we can change where we want the scrollbar to land, in my case I used a value of 0 because I want it to go to the very top of our page, but if I wanted an offset of 100px I could just type 100px in the function. So all we are really doing is animating the body of our document throughout the course of 800ms until it scrolls all the way to the top of the document. 2. Checking if images are loaded $(‘img’).load(function() { console.log(‘image load successful’); }); Sometimes you need to check if your images are fully loaded in order to continue with your scripts, this three line jQuery snippet can do that for you easily. You can also check if one particular image has loaded by replacing the img tag with an ID or class.   3. Fix broken images automatically $('img').error(function(){ $(this).attr('src', ‘img/broken.png’); }); Occasionally we have times when we have broken image links on our website and replacing them one by one isn’t easy, so adding this simple piece of code can save you a lot of headaches. Even if you don’t have any broken links adding this doesn’t do any harm.   4. Toggle class on hover $(‘.btn').hover(function(){ $(this).addClass(‘hover’); }, function(){ $(this).removeClass(‘hover’); }); We usually want to change the visual of a clickable element on our page when the user hovers over and this jQuery snippet does just that, it adds a class to your element when the user is hovering and when the user stops it removes the class, so all you need to do is add the necessary styles in your CSS file.   5. Disabling input fields $('input[type="submit"]').attr("disabled", true); On occasion you may want the submit button of a form or even one of its text inputs to be disabled until the user has performed a certain action (checking the “I’ve read the terms” checkbox for example) and this line of code accomplishes that; it adds the disabled attribute to your input so you can enable it when you want to. To do that all you need to do is run the removeAttr function on the input with disabled as the parameter: $('input[type="submit"]').removeAttr("disabled”);   6. Stop the loading of links $(‘a.no-link').click(function(e){ e.preventDefault(); }); Sometimes we don’t want links to go to a certain page or even reload it, we want them to do something else like trigger some other script and in that case this piece of code will do the trick of preventing the default action.   7. Toggle fade/slide // Fade $( “.btn" ).click(function() { $( “.element" ).fadeToggle("slow"); }); // Toggle $( “.btn" ).click(function() { $( “.element" ).slideToggle("slow"); }); Slides and Fades are something we use plenty in our animations using jQuery, sometimes we just want to show an element when we click something and for that the fadeIn and slideDown methods are perfect, but if we want that element to appear on the first click and then disappear on the second this piece of code will work just fine.   8. Make two divs the same height $(‘.div').css('min-height', $(‘.main-div').height());   9. Self-closing elements When inserting empty elements into the DOM, you can use self-closing tags: $('#el1').append('<table class="holly" />'); $('#el2').before('<p class="user-message note" />');   10. Inserting content —Before, after, prepend or append? When inserting elements into an element, use .prepend() or .append(). The difference is that prepend inserts the new element into the start (i.e. insert element as the first child), while append does the exact opposite, inserting the element as the last child: $('div').prepend('<p>Hello!</p>').append('<p>Goodbye!</p>');   11. Loopy doopy do! Very often people wonder how to loop through each element individually, and then target the current element. For this purpose, we can use .each() and $(this). Let’s say we want to add a class to all paragraphs, based on their index. If you are working on a static page, you might be tempted to hardcode it: $('p').each(function (i) {     $(this).addClass('para-' + (i+1)); } Remember that i is a zero-based index, i.e. it starts from 0 for the first encountered element.   12. Automatic vendor prefixes jQuery automatically adds vendor prefixes when it sees fit — therefore saving you the headache of adding vendor prefixes yourself: $('.box').css({ 'transform': 'translate(100,100) scale(2)' }); 13. Selectors As previously mentioned, one of the core concepts of jQuery is to select elements and perform an action. jQuery has done a great job of making the task of selecting an element, or elements, extremely easy by mimicking that of CSS. On top of the general CSS selectors, jQuery has support for all of the unique CSS3 selectors, which work regardless of which browser is being used. $('.feature');           // Class selector $('li strong');          // Descendant selector $('em, i');              // Multiple selector $('a[target="_blank"]'); // Attribute selector $('p:nth-child(2)');     // Pseudo-class selector 14. 'this' Selection Keyword When working inside of a jQuery function you may want to select the element in which was referenced inside of the original selector. In this event the this keyword may be used to refer to the element selected in the current handler. $('div').click(function(event){    $(this); });   15. jQuery Selection Filters Should CSS selectors not be enough there are also custom filters built into jQuery to help out. These filters are an extension to CSS3 and provide more control over selecting an element or its relatives. $('div:has(strong)');   16. Slide Demo //HTML <div class="panel">   <div class="panel-stage"></div>   <a href="#" class="panel-tab">Open <span>&#9660;</span></a> </div>   //Function $('.panel-tab').on('click', function(event){   event.preventDefault();   $('.panel-stage').slideToggle('slow', function(event){     if($(this).is(':visible')){       $('.panel-tab').html('Close <span>&#9650;</span>');     } else {       $('.panel-tab').html('Open <span>&#9660;</span>');     }   }); });   17. Tabs Demo //HTML <ul class="tabs-nav">   <li><a href="#tab-1">Features</a></li>   <li><a href="#tab-2">Details</a></li> </ul> <div class="tabs-stage">   <div id="tab-1">...</div>   <div id="tab-2">...</div> </div> // Show the first tab by default $('.tabs-stage div').hide(); $('.tabs-stage div:first').show(); $('.tabs-nav li:first').addClass('tab-active'); // Change tab class and display content $('.tabs-nav a').on('click', function(event){   event.preventDefault();   $('.tabs-nav li').removeClass('tab-active');   $(this).parent().addClass('tab-active');   $('.tabs-stage div').hide();   $($(this).attr('href')).show(); });   RELATED BLOGS: New Features and Highlights of Bootstrap 5

The Ultimate Guide to Bootstrap 5 Changes
Jun 29, 2020

The Bootstrap 5 alpha version has been released on June 16, 2020. You can check the official page for Bootstrap 5 alpha. Bootstrap is a free and open-source most popular CSS framework for website and web applications. It contains CSS- and (optionally) JavaScript-based design templates for typography, forms, buttons, navigation, and other interface components.HTML- and CSS-based design templates for different components of a website or application such as models, forms, buttons, navigation, accordion, tabs, typography and other interface components with helpful JavaScript extensions. A bootstrap is a powerful tool for whatever type of website and web application you are trying to build. The following are some of the expected changes in Bootstrap 5: jQuery could get removed As we all know, Bootstrap has made this decision long before. The team had opened a pull request in 2017 aiming to remove jQuery entirely from bootstrap versions, and now in bootstrap 5 alpha it is done and replaced entirely.   Switch to Vanilla JavaScript JavaScript is currently dominating the modern web development community. Almost all modern web browsers on consoles, desktops, games, tablets, and mobile phones include JavaScript interpreters. Therefore, it's geared up to become the universal scripting standard of the global.  As a result, this will improve the size and weight of the files and libraries used by the framework.   Responsive Font Sizes (RFS) Bootstrap 5 alpha enables responsive font sizes by default. That will automatically resize the typography element according to the size of the user’s viewport through RFS engine or Responsive Font Sizes. As per RFS repository, RFS is a unit resizing engine. Furthermore, RFS offers the ability to resize every value for any CSS property with units, like padding, margin, box-shadow, or border-radius.   Enhanced grid system Bootstrap 5 alpha isn’t a complete departure from v4. Developers of the first alpha have made sure that everyone can be able to upgrade to this future version more easily. Here’s a rundown of what’s new in the grid system: New grid tier: XXL ≥1400px .gutter classes have been replaced with .g* utilities. Vertical spacing classes. Columns are no longer position: relative by default. Form layout options are replaced with the new grid system. Also, options for your grid gutter spacing are added.            Here’s a quick example of how to use the new grid gutter classes: <div class="row g-5">   <div class="col">...</div>   <div class="col">...</div>   <div class="col">...</div> </div> Drop Internet Explorer 10 and 11 support Well, Internet Explorer was talk of the town when it was released as it was the only browser to support Java applets and CSS. Although it is no longer relevant with Chrome, Firefox, and Edge as it doesn’t support modern JavaScript standards and CSS properties anymore. Which limits your web design potential. Hence, Bootstrap 5 alpha decided to drop the support for IE 10 and 11.   Improved customizing docs There are some good improvisations in the documentation. Like, removing ambiguity,  giving more explanation, and providing much more support for extending Bootstrap. It all starts with a whole new Customize section. The color palette is expanded in v5, too. With an extensive color system built-in, you can more easily customize the look and feel of your app without leaving the codebase. There is an improvisation in color contrast, too. Also, they have provided color contrast metrics in Color docs. Hopefully, this will continue to help make Bootstrap-powered sites more accessible to folks all over.   The custom SVG icon library With Bootstrap 3, there were 250 reusable icon components in the font format called ‘Glyphicons”.  After that, with Bootstrap 4, it was scrapped. Because of that developers had to rely on free icon fonts or their SVG (Scalable Vector Graphic) icons to add value to their web designs. However, with Bootstrap 5 alpha, they introduced a brand new SVG icon library, which adds a fresh touch. These icons are brilliantly crafted by @Mark Otto, co-founder of Bootstrap, himself.   Adding CSS custom properties As mentioned, Bootstrap 5 alpha has begun using CSS custom properties thanks to dropping support for Internet Explorer. In v4 there were only a handful of root variables for color and fonts, and now developers have added them for a handful of components and layout options. For example table component, there are a handful of local variables to make striped, hoverable, and active table styles easier .table { --bs-table-bg: #{$table-bg}; --bs-table-accent-bg: transparent; --bs-table-striped-color: #{$table-striped-color}; --bs-table-striped-bg: #{$table-striped-bg}; --bs-table-active-color: #{$table-active-color}; --bs-table-active-bg: #{$table-active-bg}; --bs-table-hover-color: #{$table-hover-color}; --bs-table-hover-bg: #{$table-hover-bg}; // Styles here... }   Improved Utilities API  Well, this is by far the most interesting aspect of Bootstrap 5 alpha.  A brand new utility API. By using the utility API from Bootstrap you have unlimited possibilities to create utility classes for positioning, spacing, sizing, and so on. For example, you will be able to easily expand the number of `m-*`, `p-*` classes, and so on without writing custom Sass code to expand them. Here’s an example showing us how the $ utility variable can be expanded by adding multiple values: $utilities: () !default; $utilities: map-merge(   (     // ...     "width": (       property: width,       class: w,       values: (         25: 25%,         50: 50%,         75: 75%,         100: 100%,         auto: auto       )     ),     // ...     "margin": (       responsive: true,       property: margin,       class: m,       values: map-merge($spacers, (auto: auto))     ),     // ...   ), $utilities); We think this will be a game-changer for those who build on Bootstrap via source files, and if you haven’t built a Bootstrap-powered project that way yet, your mind will be blown.    Migrating the documentation from Jekyll to Hugo If you know how WordPress, Drupal, or Joomla works, then, you might be aware of how Jekyll works. Well, Jekyll is a free and open-source static site generator. Besides, it is useful to build websites with easy to use navigation, website components and generates all the content at once. However, Bootstrap 5 alpha is all set to step up its game and is switched to Hugo.  As it is a fast and flexible static site generator.   CONCLUSION One of the frustrating experiences of being a developer is reinventing the base HTML, CSS, and JavaScript for each project. While some prefer to write their code, it still makes sense to just use an existing framework like Bootstrap. With the all-new updates that came with Bootstrap 5 Alpha, We can surely say that the Bootstrap team is making very progressive steps to make the framework simple, lightweight, faster, useful, and more responsive for the developer’s benefit.   RELATED BLOGS: Easy jQuery Trick

magnusminds website loader