#handle self-closing tags in HTML
Explore tagged Tumblr posts
Text
Open-Source Social Bookmarking Software: Self-Hosting Options Explained
```html
Think about organizing your online content just like you do with your favorite books. Social bookmarking software helps with that. And when it's open-source, you have full control of your experience. This can be a game-changer for both marketing experts and beginners. At Media & Technology Group, LLC, we love to empower businesses with smart tech solutions. Here, we’ll dig into what self-hosting social bookmarking tools means and why it’s worth your attention.
What is Open-Source Social Bookmarking Software?
Let's start by clarifying what open-source social bookmarking software is. "Open-source" means that the code is free for anyone to use, change, and share. You can adjust it to your liking. Social bookmarking software helps you save, sort, and manage web pages, similar to a digital notebook. We've all got countless bookmarks scattered online, right?
Why Consider Self-Hosting?
You might ask, “Why should I self-host open-source bookmarking software?” Self-hosting gives you better control over your data. When you self-host, all your data is stored on your server or chosen cloud service, not a provider's server. You're in charge. It also boosts security, which is crucial if you're handling sensitive marketing information. We at Media & Technology Group, LLC, prioritize keeping data secure and protected.
Advantages of Self-Hosting
Enhanced Privacy: Your data is in your hands, and you control access.
Customization: Adjust the software to align with your brand and functional needs.
Cost-Effective: Post-installation, the operational costs can be lower than paying for subscription services.
Popular Open-Source Social Bookmarking Platforms
There are several standout platforms you might want to try:
1. Diigo
Diigo isn’t just a bookmarking tool; it offers highlighting and notes features. It’s well-loved by researchers and allows bookmark sharing with teams, ideal for collaborations. Diigo provides both free and premium versions, but with open-source options, you skip the limits of paid versions.
2. Shaarli
Lightweight and straightforward, Shaarli is perfect for storing links without hassle. It's great for those who aren’t tech-savvy but want some control. It’s minimalistic, cutting out unnecessary features found in more bloated software.
3. SemanticScuttle
A bit more advanced, SemanticScuttle lets you tag and organize your bookmarks. It’s useful if you have many links to manage. The platform also supports multiple users, making it excellent for a marketing team.
Steps to Self-Host Your Bookmarking Software
Worried about setup? Don’t be! Here’s a simple guide:
Choose the right software for your needs.
Prepare your server. Ensure you have a suitable server environment, like PHP or MySQL, ready.
Download and Install. Most platforms provide easy installation guides. Follow them closely.
Customize. Use the open-source code to tailor your software.
Secure it. Keep your platform and server up-to-date to avoid security risks.
Conclusion
Open-source social bookmarking software gives you freedom, adaptability, and command. Whether you’re a solo marketer or part of a larger team, self-hosting can help organize your information efficiently
0 notes
Text
HTML or XHTML: Which Syntax Will Give You Fewer Headaches?
When diving into web development, one of the first decisions you'll face is whether to use HTML or XHTML. Both are markup languages essential for creating web pages, but they come with different rules and characteristics. This guide will explore the nuances of HTML and XHTML, helping you decide which syntax might offer you fewer headaches.

Introduction
When building websites, the choice between HTML and XHTML can significantly impact your development process. Both HTML (HyperText Markup Language) and XHTML (eXtensible HyperText Markup Language) are crucial for structuring web pages, but they come with different sets of rules and features. Understanding these differences can help you avoid common pitfalls and select the syntax that best fits your needs.
What is HTML?
Definition
HTML stands for HyperText Markup Language. It is the standard language used to create and design web pages. HTML provides the basic structure of web documents by using a system of tags and attributes to define elements on the page.
History and Evolution
HTML has been around since the early days of the web. Since its inception in 1991 by Tim Berners-Lee, it has evolved through several versions. HTML5, the latest version, introduced new elements and APIs to better support modern web applications.
Basic Structure
A typical HTML document starts with a <!DOCTYPE html> declaration, followed by an <html> element that contains a <head> and a <body>. Within these sections, you can include various elements like headings, paragraphs, links, and images.
What is XHTML?
Definition
XHTML stands for eXtensible HyperText Markup Language. It combines the flexibility of HTML with the strict syntax rules of XML (eXtensible Markup Language). XHTML aims to improve web standards and ensure consistent rendering across different browsers.
Differences from HTML
While XHTML is similar to HTML, it enforces stricter rules. For example, XHTML documents must be well-formed XML documents, meaning they must adhere to precise syntax rules such as proper tag closure and case sensitivity.
Basic Structure
An XHTML document also begins with a <!DOCTYPE html> declaration but requires all tags to be properly closed and nested. It follows a more rigorous syntax compared to HTML.
Key Differences Between HTML and XHTML
Syntax Rules
HTML is more lenient with syntax rules. For example, tags can be left unclosed, and attribute values can be omitted if they are boolean. XHTML, on the other hand, requires all tags to be closed and attributes to be quoted.
Case Sensitivity
HTML is not case-sensitive. Tags and attributes can be written in any combination of uppercase and lowercase letters. XHTML requires all tags and attributes to be in lowercase.
Tag Closure
In HTML, some tags like <br> or <img> don’t require closing tags. XHTML mandates that all tags must be closed, either with a separate closing tag or a self-closing slash (e.g., <br />).
Advantages of HTML
Flexibility
HTML's flexibility allows for faster development and easier adjustments. Developers can write less strict code without worrying about compliance issues.
Browser Compatibility
HTML has broad compatibility with various browsers. Older browsers and newer ones alike generally support HTML, making it a safe choice for many projects.
Ease of Use
For beginners, HTML is easier to learn and use. Its less strict rules mean fewer errors during development.
Advantages of XHTML
Strict Syntax Rules
XHTML’s strict syntax rules help ensure that documents are well-formed and free of errors. This can lead to more predictable rendering and easier debugging.
Compatibility with XML
Since XHTML is based on XML, it integrates well with other XML-based technologies. This can be beneficial for projects that require data interchange between different systems.
Error Handling
XHTML provides better error handling due to its stricter rules. Errors are often easier to identify and fix compared to HTML.
Common Issues with HTML
Browser Inconsistencies
HTML’s lenient syntax can lead to inconsistencies in how different browsers render the same page. This may require additional testing and adjustments.
Deprecated Elements
Some HTML elements and attributes have become outdated. Using these can lead to issues with modern browsers and may impact future-proofing your website.
Common Issues with XHTML
Strict Compliance Requirements
The strict rules of XHTML can be challenging, especially if you’re used to HTML’s more relaxed approach. Small mistakes, like forgetting to close a tag, can cause your entire document to fail.
Potential for More Errors
Due to its stricter nature, XHTML can lead to more frequent errors during development. This requires more careful coding and validation.
When to Use HTML
Simple Projects
HTML is suitable for straightforward projects where the flexibility and ease of use outweigh the need for strict standards.
Legacy Systems
For maintaining older websites that were originally built with HTML, sticking with HTML might be easier and more practical.
When to Use XHTML
Complex Projects
If you’re working on a complex project that requires rigorous data handling or integration with other XML-based technologies, XHTML might be the better choice.
XML-Based Applications
For applications that need to comply with XML standards, XHTML provides the necessary structure and error handling.
Best Practices for Using HTML and XHTML
Writing Clean Code
Regardless of the syntax you choose, writing clean and organized code is crucial. It makes your code more readable and maintainable.
Validating Your Code
Use validation tools to check your HTML or XHTML code. This helps catch errors early and ensures your code meets the standards.
Staying Updated with Standards
Web standards evolve, so stay informed about the latest developments in HTML and XHTML to keep your skills and code current.
Conclusion
Choosing between HTML and XHTML depends on your project requirements and personal preferences. HTML offers flexibility and ease of use, while XHTML provides strict syntax rules and compatibility with XML. Consider the complexity of your project, the need for strict standards, and your own comfort level with these languages when making your decision.
FAQs
What are the main differences between HTML and XHTML?
HTML is more flexible and less strict with syntax, while XHTML enforces stricter rules and is XML-based.
Can I mix HTML and XHTML in the same document?
No, mixing HTML and XHTML in the same document can lead to errors. Stick to one syntax for consistency.
Which is better for mobile web development?
Both HTML and XHTML can be used for mobile web development, but HTML5 is often preferred due to its modern features and flexibility.
How do I transition from HTML to XHTML?
To transition, start by ensuring your HTML is well-formed and follows XHTML rules. Use validation tools to check for compliance.
Are there any tools to help with HTML or XHTML validation?
Yes, tools like W3C Markup Validation Service and HTML Tidy can help validate and clean up your code.
1 note
·
View note
Photo
⠀ ⠀⠀ ❝ Hello my name is Sheep ❞ ⠀ ⠀⠀ ⠀ ⠀⠀ This is a minimal effort, casual, and a creative roleplay writing blog. Expect high quality content, crack, and low effort in html or stylizing. I just want to write and have a good time - and so: if you expect that then I have nothing to impress anyone over. I write for many fandoms, and have a plethora of flexibility. Come take my hand and join me.
⠀ ⠀⠀ Lazy Muse List : https://mused.carrd.co/#gamestart
⠀ ⠀⠀▐ ⋮ ⅰ . } I roleplay here casually and prioritize my close friends. Outside of Tumblr; I work, on savage content/ultimate content on FFXIV, roleplay on dreamwidth, and focus a lot of energy on my art or creative writing.
⠀ ⠀⠀▐ ⋮ ⅱ . } I will always keep a tag/thread going if it is plotted with intention of growth. If it is a random roleplay thread for fun, or a response on the dashboard. I wont always follow up with it.
⠀ ⠀⠀▐ ⋮ ⅲ . } It is common to get short small paragraph roleplays with me, as I enjoy conversational threads.
⠀ ⠀⠀▐ ⋮ ⅳ . } SHIPPING ; Primarily a CIS MALE & CIS FEMALE heterosexual roleplayer. I enjoy some WlW, but ask that you approach me about any lgbtqia+ interests. Irl I am CIS FEMALE, Demiace heterosexual. With a nonsexual love over women. So long as you dont impose enjoying women sexually onto me - I will enjoy writing WlW or even MlM. ⠀ ⠀⠀ ⠀ ⠀⠀ADDITONALLY, for my G’raha Tia or Crystal Exarch muse - or anyone else as I plan to pick up Hauchefaunt as well. I will default them to being with my own Warrior of Light. I will HAPPILY roleplay WolxCanon stuff with the importance and stress on getting to know the mun individually/as well as the character them self. Unless we are friends already. The basics of shipping is important to me, and I do not like having to adapt headcanons of wolxcanon stuff that I know nothing about! It just wont make for good rp. IE just rp with me literally and we will see it happen!
⠀ ⠀⠀▐ ⋮ ⅳ . } NOTPS: Do not TALK to me, follow me, or acknowledge my existence of you ship SCARAMONA(Scaramouche / Mona ) or Diluc / Kaeya. Thank you.
⠀ ⠀⠀▐ ⋮ ⅴ . } Triggers: ⠀ ⠀⠀ ⠀ ⠀⠀ Fetishizing: Pedohilia, incest, and zoophilia (Furry/dragons/etc is not zoophilia). ⠀ ⠀⠀ ⠀ ⠀⠀ Selfcest is trigger in my mind as incest, so do not ever try to involve me in anything like this. This is my only trigger, and am okay with anything else that is consensual between muns and properly tagged/handled. ⠀ ⠀⠀ ⠀ ⠀⠀Do not defend abusers.
⠀ ⠀⠀▐ ⋮ ⅵ . } Overall, if I feel other information is necessary I will add. However, I am easy going and enjoy writing anything so hit me up freely.
#rp promo#pinned#sheepcringegrahasimp#genshin roleplay#ffxiv roleplay#danganronpa roleplay#fate roleplay#typemoon roleplay
12 notes
·
View notes
Text
Render HTML with Scalable Column Width & Get Connection Points from Shapes using .NET
What’s new in this release?
Aspose development team is pleased to announce the new release of Aspose.Cells for .NET 18.10. MS Excel file formats API that provides the ability to create, manipulate, convert or render MS Excel spreadsheets, and more importantly – is fully documented. Please check the document on how to install Aspose for .NET APIs directly from NuGet repository.It has added a few important features while keeping the product more stable and feature rich API. In this release, It has also added some useful enhancements and resolved a number of issues. Sometimes when some bug or issue is reported, that guides us to provide some new feature or enhancement thus making this product more user friendly and capable of solving complex problems in an easier way. Simple features which become quite handy while working with a complex product are added like providing last saved time property for keeping track of changes etc. Depiction of data through HTML page is very common, however this page can be opened in a variety of devices including mobiles, tabs and other hand held devices which contain small screens. The size of the columns is defined in “pt” which works in many cases. However there can be case where this fixed size may not be required. For example, if container panel width is 600px where this HTML page is being displayed. In this case you may get horizontal scrollbar if the generated table width is bigger. This requirement is addressed by providing scalable units like em or percent for a better presentation. Empty tags are very common while working with HTML like we can face <td></td> or simply <td/>. Earlier self-closing tags were not supported however now this support is provided. Now you can load any HTML with self-closing tags and convert it to Excel file. Named regions can have English formulae and this file can be used in environments where systems are configured to German locale. There is need to translate these English formulae completely to German language for correct usage in MS Excel configured for German language. This feature is fully functional and can be used without any extra coding. MS Excel provides custom filters like filter rows which begins with and ends with some specific string. This feature is available in Aspose.Cells and demonstrated by providing working examples. Aspose.Cells provide rich features to manage shapes in the spreadsheet. Sometimes there is need to get the connection points of a shape for aligning or placing the shapes at appropriate place. For this purpose all the connection points are required. Following code can be used to get the list of connection points of a shape where Shape.GetConnectionPoints() function is used. There are some other enhancements included and a few exceptions handled in the new release for the users. A few of the worth mentioning features and other improvements , such as Using preferred parser and Handled an exception which occurred when loading an Excel file. In Aspose.Cells 18.10, we fixed several important bugs and other issues. For example, issues around reading/writing MS Excel file formats, applying data filtering, manipulating OLE Objects, reading/writing HTML files, manipulating List Objects/Tables, applying auto-fit rows/columns, formatting cells, Smart Markers, manipulating document properties, rendering and manipulating charts and shapes, rendering images from Excel worksheets, rendering images files from charts and exporting Excel workbooks to PDF format have been resolved in the release. This release includes several enhanced features and bug fixes as listed below
Get connection points from shapes
Change columns' fixed size width (i.e., pt/px) into scalable unit like "em" or "percent"
Issue with the image source when rendering Excel to HTML file format
Font size changed from 6.5 to 6 while converting XLSX to HTML
Recognize empty tags like <td /> while converting HTML to MS Excel file format
Sub-Total missing when rows collapsed after refresh
Issue in number fields while calling the Worksheet.AutoFitColumns()
XLSB file gets corrupt on opening and saving
CSV import creates incorrect formatting using PreferredParsers
"_xll" attached in front of formula name
Named range formula ("=GET.CELL") not properly created in German locale
Escape character is displayed as it is in PDF
PDF output page size(and margins) doesn't match MS Excel output
Height of image in header truncated along with broken layout during XLSM->PDF conversion
Image not repeating properly when print titles are set for rows and columns
Rendering image from a simple chart takes all resources and then raises exception
Accessing visibility properties changed the visibility of the chart in the re-saved output
SourceFullName property of OLE Object is empty while accessing in XLSB
Header picture/shape is not rendered correctly when re-saving an XLSX file
Difference in OLE Objects before and after saving the XLSB file
Phonetic guide missing after copy and save
Resizing tables changes format of cells
Wrong detection of cell foreground and background color
Autofit happens automatically to the hidden rows when rows are auto filtered
Custom scheme 'm-files://...' is converted in document save-operation
XLSB files cannot be opened using LoadDataFilterOption other than LoadDataFilterOption.All
Formula missing single quote
LoadDataFilterOptions.SheetSettings not working for XLSB files
View is changed to protected while converting XLS -> XLSM -> XLS
XLSX file is corrupt after converting from an XML (SpreadsheetML) file
Smart Marker does not evaluate ISBLANK properly
FilterOperatorType.Contains missing from API
Other most recent bug fixes are also included in this release
Newly added documentation pages and articles
Some new tips and articles have now been added into Aspose.Cells for .NET documentation that may guide users briefly how to use Aspose.Cells for performing different tasks like the followings.
Recognize self-closing tags
Support for German Locale in Named Range Formulae
Overview: Aspose.Cells for .NET
Aspose.Cells is a .NET component for spreadsheet reporting without using Microsoft Excel. It supports robust formula calculation engine, pivot tables, VBA, workbook encryption, named ranges, spreadsheet formatting, drawing objects like images, OLE objects and importing or creating charts. You can also create Excel file using designer spreadsheet, smart marker or API and apply formulae and functions. It supports CSV, SpreadsheetML, PDF and all file formats from Excel 97 to Excel 2007.
More about Aspose.Cells for .NET
Homepage of Aspose.Cells for .NET C#
Download Aspose.Cells for .NET
Online documentation of Aspose.Cells for .NET
#Render HTML with scalable column width#create custom filters#get connection points from shapes#handle self-closing tags in HTML#German locale in Named Range Formulae#.NET Excel API
0 notes
Text
React JS
PropTypes: PropTypes imply that components use the correct data type and pass the right data. And it is further understood that these components use the right kind of props and the obtained components get the right kind of props.
State-props: The main difference between props and states is that states are internal and controlled by components.
JSX: JSX is an inline markup that looks like HTML but is converted to JavaScript. JSX expressions start with HTML-like open tags and end with closing tags. JSX tags support XML self-close syntax so that the closing tag can be optional.
Component Lifecycle: Each element of the reaction has a life cycle that we can observe and manipulate in its three main stages. There are three stages: Mounting, Updating, and Unmounting.
Hooks: React Hook is a simple JavaScript function that is included inside the React library. These functions are similar to Hooks and can be used with React Hooks where needed.
Custom hooks: A custom hook is a JavaScript function. This custom hook is used to share arguments among other JavaScript functions. We make custom hooks ourselves.
Example: import { useEffect, useState} from "react"
const addProducts = ()=>{
const [ products, setProducts] = useState([]);
useEffect(()=>{
fetch('./product.JSON')
.then(res=>res.json())
.then(data=> setProducts(data));},[])
return [ products, setProducts ];}
Context API: Context API is used to send the components of the app through props from any place in any way from the app
Virtual DOM: Virtual DOM is a programming concept where the UI is stored in “virtual” representative memory and matched to the actual DOM through a library like ReactDOM. A virtual DOM and a real DOM have the same features. Real DOM manipulation is slow and virtual DOM manipulation is much faster.
How do events work in react: The rules for managing events with React elements are the same as the rules for managing events with DOM elements. But there are some syntax differences: React events are named using camelCase, rather than lowercase.
Higher order component: A higher-order component is an advanced technique in React for reusing component logic. The examples of Higher-order components are Redux's connect and Relay's createContainer.
useEffect and useState: useState allows our functional components which used to be stateless become stateful. And useEffect allows our functional components to leverage component lifecycle hooks.
Events: The rules for managing events with React elements are the same as the rules for managing events with DOM elements. But there are some syntax differences: React events are named using camelCase, rather than lowercase.
Flux Concept: Flux concepts is a new kind of architecture that complements React and the concept of Unidirectional Data Flow.
Fragments: Fragment keywords are used to group a list of children components without using any additional nodes in the DOM.
Prop drilling: Prop drilling is the process of a React app where props can easily pass data from one component to another.
Conditional rendering: conditional rendering refers to the dynamic output of user interface markups based on a condition. Using conditional rendering, it is possible to toggle specific application functions, API data rendering, hide or show elements, decide permission levels, authentication handling, and so on.
React advantages and disadvantages:
Advantages:
1/ JavaScript code much easier.
2/ Cross-platform support.
3/ Templates can be designed much easier. 4/ Provides amazing developer tools. 5/ UI focused design.
6/ Easy to accept.
Disadvantages:
1/ Lack of Documentation.
2/ It only covers the UI so other languages are needed to create a complete application.
3/ The high speed of development makes the life of the developer difficult.
Optimize a react js application: Here's what to do to optimize a react js application:
1. Large bundle size.
2. Large rendering.
3. unnecessary rendering.
4. Download on demand. There are many more things to keep in mind, including the above.
Empty tags: Empty tag is used to declare fragments in React.
Most common approaches for styling a React application: The most common approaches for styling a React application are:
1/ CSS Classes
2/ Inline CSS
3/ Pre-processors Such as Sass, Stylus, and Less
4/ CSS-in-JS Modules Such as Styled Components, Emotion, and Styled-JSX.
#programmer sajeeb#programmer#coder#reactjs#PropTypes#State-props#JSX#Component Lifecycle#Hooks#Custom hooks#Context API#Virtual DOM#How do events work in react#Higher order component#useEffect and useState#Events#Flux Concept#Fragments#Prop drilling#Conditional rendering#React advantages and disadvantages#Advantages#Disadvantages#Optimize a react js application#Most common approaches for styling a React application
1 note
·
View note
Text
Implementation of dark mode in reaction devices
One of the apps features most requested is the dark mode (or night mode, as others call it). In the apps which we use every day, we see dark mode. From smartphones to web applications, the dark mode has become important to businesses wishing to look after their users' eyes.The dark mode is an add-on feature that often shows dark surfaces in the UI. Most big corporations (such as YouTube, Twitter, and Netflix) have brought their smartphone and web applications into dark mode.Although we are not going to go into React and styled-components in detail, a simple knowledge of React, CSS, and styled-components would be useful.
A few days before this article was written, StackOverflow announced its release of dark mode, offering users the opportunity to switch between the two modes.Dark mode eliminates eye pressure and aids when operating on a device or cell phone for a long period of time. What Is Dark Mode?The dark mode is the color scheme of any device showing light text and device elements on a dark backdrop, making it a little easier for the user to view cell phones, tablets, and computers. Dark mode decreases the light produced by the screen while preserving the minimum color-contrast ratios that are appropriate for reading. Why Should You Care About Dark Mode?Dark mode improves visual ergonomics by reducing eye strain, adapting the screen to current light conditions, and ensuring ease of use in dark environments or at night.Let's look at its benefits before we introduce dark mode in our app.
BATTERY SAVINGDark mode in Web and mobile apps will extend a device's battery life. Google stated that dark mode on OLED screens has been a tremendous help to battery life.For example, the dark mode in the YouTube app saves about 15 percent more screen energy than a flat white background at 50 percent brightness. The dark GUI saves a whopping 60 percent of screen energy at 100 percent screen brightness. DARK MODE IS BEAUTIFULThe dark mode is stunning, and can greatly enhance the screen's appeal.Although most products go for the same bland white look, the dark mode offers something else that looks both mysterious and fresh.It also offers great opportunities for a fresh presentation of graphic material, such as dashboards, videos, and images.
Now that you know why you should implement dark mode in your next web app, let's dive deep into style-components, which in this tutorial's defining resources.The dark mode is the color scheme of any interface that displays light text and interface elements on a dark background, making viewing on mobile phones, tablets, and computers a little easier.
What Are Styled-Components?We will be using the styled-components library very much in this post. There have always been a lot of ways to design a modern web application. A document-level there is the conventional styling approach which involves creating an index.css file and linking it to the HTML or styling within the HTML file.A lot has changed in the way web apps are recently designed after CSS-in-JS was introduced.CSS-in-JS refers to a pattern where JavaScript is used to compose the Html. To style components in a JavaScript file, it uses tagged template literals. The styled component is a CSS-in-JS library that allows you to use all the
CSS
features you need, including media queries, pseudo-selectors, and nesting.
Why Styled-Components?For the following reasons styled-components were created:
No hell class name Instead of scratching your head to find an item class name, styled-components can create unique class names for your types. You will never have to think about misrepresentations, or using class names that have no meaning.
The use of designed component props allows one to expand the styling properties using the props parameter widely used in React — thereby dynamically influencing the component's feeling through the state of the application. Supports Sass syntax
Writing Sass syntax out of the box without having to set up any preprocessors or extra build tools is possible with styled-components. In your style definitions, you can use the & character to target the current component, use pseudo-selectors, and experiment with nesting.
• Theming modeled components have full thematic support through the export of a ThemeProvider wrapper. This framework provides a theme for all components of React within itself via the Context API. All styled-components will have access to the given theme in the rendering tree, even though they are deeply multi-level. As we continue this tutorial, we will investigate the thematic features of modeled components more deeply SETTING UP
1. CREATE THE FILE STRUCTURECreating a folder and inserting within it three empty text files: one with.html, one with.css, and one with.js. Also, create a folder of images for the photos you wish to view on the website.JQuery also makes use of our "dark mode in CSS" demo. In the example, we are going to add the script right from the Cloudflare CDN to the HTML file so that it is always up to date. If you like, however, you can download and add the jQuery library as a local.js file as well.Here's how the file structure will look before coding begins:
- dark-mode-css/ - images/ - cake.jpg - index.html - script.js - style.css
2. MARK UP THE HTMLAdd the dark-mode switch to the top of the page in the HTML. Then create a < h1 > title tag, and a semantic < article > tag for the page's content. Finally, just before the < /body > tag closes add the two < script > tags.Please note that before the custom script you are adding the jQuery library so it can use its functionalities. The style.css file will go into the page's < head > section.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Demo | Dark Mode in CSS</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="switch">Dark mode: <span class="inner-switch">OFF</span> </div> <h1 class="title">The Best Recipes of All Time</h1> <article> <h1>Raspberry Cake</h1> <p><small>Created with Cupcake Ipsum</small></p> <p>...</p> <img src="images/cake.jpg"> <p>...</p> </article> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="script.js"></script> </body> </html>
3. CREATE THE CSS FOR THE LIGHT MODEFirst, let's build the CSS for light mode, since this is the page's default state. The following CSS makes use of a column-based flexbox style that allows you to easily place elements on the page, specifically the.switch class that handles the dark mode toggle wrapper and the < img > elements.
body { font-family: sans-serif; font-size: 1.125rem; display: flex; flex-direction: column; max-width: 50rem; margin: 0 auto; padding: 0 0.9375rem; } small { font-style: italic; } article { display: flex; flex-direction: column; } img { max-width: 100%; display: block; align-self: center; } .switch { align-self: flex-end; margin: 0.9375rem; } .inner-switch { display: inline-block; cursor: pointer; border: 1px solid #555; border-radius: 1.25rem; width: 3.125rem; text-align: center; font-size: 1rem; padding: 0.1875rem; margin-left: 0.3125rem; }
The display: flex; rule applied to the tag allows the align-self to be used: flex-end; rule over the dark mode turn. The align-self CSS property aligns individual flex elements along the cross-axis (which is the left-to-right axis when a column is set to flex-direction).In this way, the move is located automatically to the top right corner of the flex container — for all viewport sizes. .switch is a full-width layout row due to the flexbox, and its height does not fall at smaller screen sizes either.Similarly, the display: flex; and flex-direction: column; rules added to the < article > tag allow align-self to be used: center; rule on all images inside the post. As a result, all the images can be conveniently focused without adding extra elements to the HTML, only for positioning purposes. 4. ADD THE SWITCH FUNCTIONALITY WITH JQUERYThe.js script file provides the toggle switch feature. Therefore, the dark mode is activated when the user clicks the toggle and the mark on the switch switches to "ON." And if, when the page is in dark mode, the user clicks the toggle, the light mode is added and the mark switches to "OFF."
$( ".inner-switch" ).on("click", function() { if( $( "body" ).hasClass( "dark" )) { $( "body" ).removeClass( "dark" ); $( ".inner-switch" ).text( "OFF" ); } else { $( "body" ).addClass( "dark" ); $( ".inner-switch" ).text( "ON" ); } });
The script above makes use of the following jQuery functions:·
on(“click”, function() {…})
is an event handler that triggers the action inside the function when the user clicks the .inner-switch element,·
hasClass()
checks if the .dark class is assigned to the .inner-switch element or not (this is based on the state of the toggle),·
removeClass()
removes the .dark class from the HTML when the user switches to light mode,·
addClass()
adds the .dark class to the HTML when the user switches to dark mode,·
text()
sets the text of the label on the switch — it’s either “OFF” or “ON”.· 5. ADD THE CSS FOR THE DARK MODEThe last thing you need to do is to define those styles for the.dark class that the jQuery script above added to the HTML when dark mode is turned on. In addition to the.dark class, apply the dark mode theme to both its direct and indirect children using the.dark * universal CSS selector.
.dark, .dark * { background-color: #222; color: #e6e6e6; border-color: #e6e6e6; }
The CSS belonging to the.dark class goes to the file ending with style.css. This is because CSS (= Cascading Style Sheets) is cascading in nature. The cascade may thus bypass the colors all over the page without bumping into specificity or other probelms.You can also create a separate dark.css file for the dark mode styles if you are creating a more complex website. In this case, be careful that you always add the unique dark.css in the < head > section of the HTML after the generic style.css file, so that the cascade will work properly.
CREATING THEME-TOGGLING FUNCTIONALITY1. Add HTML:Using any item that should store the content for which you want the interface toggle. In our case, for simplicity we'll use < body >:
Example
<body>
Add CSS:Design the item < body > and build a toggle class in.dark-mode:
Example
body { padding: 25px; background-color: white; color: black; font-size: 25px; } .dark-mode { background-color: black; color: white; }
3) Add JavaScript:Get the < body > item and switch between the class of dark-mode:
Example
function myFunction() { var element = document.body; element.classList.toggle("dark-mode"); }
ConclusionDark mode is increasingly becoming a choice for the consumer, and it is much easier to integrate it into a web app by using the Theme Provider theme wrapper in styled components. Go ahead and play with styled-components as you implement dark mode; you could add icons instead of a button.
As a reputed Software Solutions Developer we have expertise in providing dedicated remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to
get in touch with us!
#b2b ecommerce
#b2b content marketing
#b2b market research companies
#b2b seo
#Ecommerce
0 notes
Text
Implementation of Dark Mode in React Devices
One of the apps features most requested is the dark mode (or night mode, as others call it). In the apps which we use every day, we see dark mode. From smartphones to web applications, the dark mode has become important to businesses wishing to look after their users' eyes.The dark mode is an add-on feature that often shows dark surfaces in the UI. Most big corporations (such as YouTube, Twitter, and Netflix) have brought their smartphone and web applications into dark mode.Although we are not going to go into React and styled-components in detail, a simple knowledge of React, CSS, and styled-components would be useful.
A few days before this article was written,
StackOverflow
announced its release of dark mode, offering users the opportunity to switch between the two modes.Dark mode eliminates eye pressure and aids when operating on a device or cell phone for a long period of time. What Is Dark Mode?The dark mode is the color scheme of any device showing light text and device elements on a dark backdrop, making it a little easier for the user to view cell phones, tablets, and computers. Dark mode decreases the light produced by the screen while preserving the minimum color-contrast ratios that are appropriate for reading. Why Should You Care About Dark Mode?Dark mode improves visual ergonomics by reducing eye strain, adapting the screen to current light conditions, and ensuring ease of use in dark environments or at night.Let's look at its benefits before we introduce dark mode in our app.
BATTERY SAVINGDark mode in Web and mobile apps will extend a device's battery life. Google stated that dark mode on OLED screens has been a tremendous help to battery life.For example, the dark mode in the YouTube app saves about 15 percent more screen energy than a flat white background at 50 percent brightness. The dark GUI saves a whopping 60 percent of screen energy at 100 percent screen brightness. DARK MODE IS BEAUTIFULThe dark mode is stunning, and can greatly enhance the screen's appeal.Although most products go for the same bland white look, the dark mode offers something else that looks both mysterious and fresh.It also offers great opportunities for a fresh presentation of graphic material, such as dashboards, videos, and images.
Now that you know why you should implement dark mode in your next web app, let's dive deep into style-components, which in this tutorial's defining resources.The dark mode is the color scheme of any interface that displays light text and interface elements on a dark background, making viewing on mobile phones, tablets, and computers a little easier.
What Are Styled-Components?We will be using the styled-components library very much in this post. There have always been a lot of ways to design a modern web application. A document-level there is the conventional styling approach which involves creating an index.css file and linking it to the HTML or styling within the HTML file.
A lot has changed in the way web apps are recently designed after CSS-in-JS was introduced.
CSS-in-JS refers to a pattern where JavaScript is used to compose the Html. To style components in a JavaScript file, it uses tagged template literals. The styled component is a CSS-in-JS library that allows you to use all the CSS features you need, including media queries, pseudo-selectors, and nesting.
Why Styled-Components?For the following reasons styled-components were created:
No hell class name Instead of scratching your head to find an item class name, styled-components can create unique class names for your types. You will never have to think about misrepresentations, or using class names that have no meaning.
The use of designed component props allows one to expand the styling properties using the props parameter widely used in React — thereby dynamically influencing the component's feeling through the state of the application. Supports Sass syntax
Writing Sass syntax out of the box without having to set up any preprocessors or extra build tools is possible with styled-components. In your style definitions, you can use the & character to target the current component, use pseudo-selectors, and experiment with nesting.
• Theming modeled components have full thematic support through the export of a ThemeProvider wrapper. This framework provides a theme for all components of React within itself via the Context API. All styled-components will have access to the given theme in the rendering tree, even though they are deeply multi-level. As we continue this tutorial, we will investigate the thematic features of modeled components more deeply SETTING UP1. CREATE THE FILE STRUCTURECreating a folder and inserting within it three empty text files: one with.html, one with.css, and one with.js. Also, create a folder of images for the photos you wish to view on the website.JQuery also makes use of our "dark mode in CSS" demo. In the example, we are going to add the script right from the Cloudflare CDN to the HTML file so that it is always up to date. If you like, however, you can download and add the jQuery library as a local.js file as well.Here's how the file structure will look before coding begins:
- dark-mode-css/ - images/ - cake.jpg - index.html - script.js - style.css
2. MARK UP THE HTMLAdd the dark-mode switch to the top of the page in the HTML. Then create a < h1 > title tag, and a semantic < article > tag for the page's content. Finally, just before the < /body > tag closes add the two < script > tags.Please note that before the custom script you are adding the jQuery library so it can use its functionalities. The style.css file will go into the page's < head > section.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Demo | Dark Mode in CSS</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="switch">Dark mode: <span class="inner-switch">OFF</span> </div> <h1 class="title">The Best Recipes of All Time</h1> <article> <h1>Raspberry Cake</h1> <p><small>Created with Cupcake Ipsum</small></p> <p>...</p> <img src="images/cake.jpg"> <p>...</p> </article> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="script.js"></script> </body> </html>
3. CREATE THE CSS FOR THE LIGHT MODEFirst, let's build the CSS for light mode, since this is the page's default state. The following CSS makes use of a column-based flexbox style that allows you to easily place elements on the page, specifically the.switch class that handles the dark mode toggle wrapper and the < img > elements.
body { font-family: sans-serif; font-size: 1.125rem; display: flex; flex-direction: column; max-width: 50rem; margin: 0 auto; padding: 0 0.9375rem; } small { font-style: italic; } article { display: flex; flex-direction: column; } img { max-width: 100%; display: block; align-self: center; } .switch { align-self: flex-end; margin: 0.9375rem; } .inner-switch { display: inline-block; cursor: pointer; border: 1px solid #555; border-radius: 1.25rem; width: 3.125rem; text-align: center; font-size: 1rem; padding: 0.1875rem; margin-left: 0.3125rem; }
The display: flex; rule applied to the tag allows the align-self to be used: flex-end; rule over the dark mode turn. The align-self CSS property aligns individual flex elements along the cross-axis (which is the left-to-right axis when a column is set to flex-direction).In this way, the move is located automatically to the top right corner of the flex container — for all viewport sizes. .switch is a full-width layout row due to the flexbox, and its height does not fall at smaller screen sizes either.Similarly, the display: flex; and flex-direction: column; rules added to the < article > tag allow align-self to be used: center; rule on all images inside the post. As a result, all the images can be conveniently focused without adding extra elements to the HTML, only for positioning purposes. 4. ADD THE SWITCH FUNCTIONALITY WITH JQUERYThe.js script file provides the toggle switch feature. Therefore, the dark mode is activated when the user clicks the toggle and the mark on the switch switches to "ON." And if, when the page is in dark mode, the user clicks the toggle, the light mode is added and the mark switches to "OFF."
$( ".inner-switch" ).on("click", function() { if( $( "body" ).hasClass( "dark" )) { $( "body" ).removeClass( "dark" ); $( ".inner-switch" ).text( "OFF" ); } else { $( "body" ).addClass( "dark" ); $( ".inner-switch" ).text( "ON" ); } });
The script above makes use of the following jQuery functions:·
on(“click”, function() {…})
is an event handler that triggers the action inside the function when the user clicks the .inner-switch element,·
hasClass()
checks if the .dark class is assigned to the .inner-switch element or not (this is based on the state of the toggle),·
removeClass()
removes the .dark class from the HTML when the user switches to light mode,·
addClass()
adds the .dark class to the HTML when the user switches to dark mode,·
text()
sets the text of the label on the switch — it’s either “OFF” or “ON”.· 5. ADD THE CSS FOR THE DARK MODEThe last thing you need to do is to define those styles for the.dark class that the jQuery script above added to the HTML when dark mode is turned on. In addition to the.dark class, apply the dark mode theme to both its direct and indirect children using the.dark * universal CSS selector.
.dark, .dark * { background-color: #222; color: #e6e6e6; border-color: #e6e6e6; }
The CSS belonging to the.dark class goes to the file ending with style.css. This is because CSS (= Cascading Style Sheets) is cascading in nature. The cascade may thus bypass the colors all over the page without bumping into specificity or other probelms.You can also create a separate dark.css file for the dark mode styles if you are creating a more complex website. In this case, be careful that you always add the unique dark.css in the < head > section of the HTML after the generic style.css file, so that the cascade will work properly.CREATING THEME-TOGGLING FUNCTIONALITY1. Add HTML:Using any item that should store the content for which you want the interface toggle. In our case, for simplicity we'll use < body >:Example<body> Add CSS:Design the item < body > and build a toggle class in.dark-mode:Example
body { padding: 25px; background-color: white; color: black; font-size: 25px; } .dark-mode { background-color: black; color: white; }
3) Add JavaScript:Get the < body > item and switch between the class of dark-mode:Example
function myFunction() { var element = document.body; element.classList.toggle("dark-mode"); }
ConclusionDark mode is increasingly becoming a choice for the consumer, and it is much easier to integrate it into a web app by using the ThemeProvider theme wrapper in styled components. Go ahead and play with styled-components as you implement dark mode; you could add icons instead of a button.
As a reputed Software Solutions Developer we have expertise in providing dedicated remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to
get in touch with us!
0 notes
Text
Implementation of dark mode in reaction devices
One of the apps features most requested is the dark mode (or night mode, as others call it). In the apps which we use every day, we see dark mode. From smartphones to web applications, the dark mode has become important to businesses wishing to look after their users' eyes.The dark mode is an add-on feature that often shows dark surfaces in the UI. Most big corporations (such as YouTube, Twitter, and Netflix) have brought their smartphone and web applications into dark mode.Although we are not going to go into React and styled-components in detail, a simple knowledge of React, CSS, and styled-components would be useful.
A few days before this article was written, StackOverflow announced its release of dark mode, offering users the opportunity to switch between the two modes.Dark mode eliminates eye pressure and aids when operating on a device or cell phone for a long period of time. What Is Dark Mode?The dark mode is the color scheme of any device showing light text and device elements on a dark backdrop, making it a little easier for the user to view cell phones, tablets, and computers. Dark mode decreases the light produced by the screen while preserving the minimum color-contrast ratios that are appropriate for reading. Why Should You Care About Dark Mode?Dark mode improves visual ergonomics by reducing eye strain, adapting the screen to current light conditions, and ensuring ease of use in dark environments or at night.Let's look at its benefits before we introduce dark mode in our app.
BATTERY SAVINGDark mode in Web and mobile apps will extend a device's battery life. Google stated that dark mode on OLED screens has been a tremendous help to battery life.For example, the dark mode in the YouTube app saves about 15 percent more screen energy than a flat white background at 50 percent brightness. The dark GUI saves a whopping 60 percent of screen energy at 100 percent screen brightness. DARK MODE IS BEAUTIFULThe dark mode is stunning, and can greatly enhance the screen's appeal.Although most products go for the same bland white look, the dark mode offers something else that looks both mysterious and fresh.It also offers great opportunities for a fresh presentation of graphic material, such as dashboards, videos, and images.
Now that you know why you should implement dark mode in your next web app, let's dive deep into style-components, which in this tutorial's defining resources.The dark mode is the color scheme of any interface that displays light text and interface elements on a dark background, making viewing on mobile phones, tablets, and computers a little easier.
What Are Styled-Components?We will be using the styled-components library very much in this post. There have always been a lot of ways to design a modern web application. A document-level there is the conventional styling approach which involves creating an index.css file and linking it to the HTML or styling within the HTML file.A lot has changed in the way web apps are recently designed after CSS-in-JS was introduced.CSS-in-JS refers to a pattern where JavaScript is used to compose the Html. To style components in a JavaScript file, it uses tagged template literals. The styled component is a CSS-in-JS library that allows you to use all the
CSS
features you need, including media queries, pseudo-selectors, and nesting.
Why Styled-Components?For the following reasons styled-components were created:
No hell class name Instead of scratching your head to find an item class name, styled-components can create unique class names for your types. You will never have to think about misrepresentations, or using class names that have no meaning.
The use of designed component props allows one to expand the styling properties using the props parameter widely used in React — thereby dynamically influencing the component's feeling through the state of the application. Supports Sass syntax
Writing Sass syntax out of the box without having to set up any preprocessors or extra build tools is possible with styled-components. In your style definitions, you can use the & character to target the current component, use pseudo-selectors, and experiment with nesting.
• Theming modeled components have full thematic support through the export of a ThemeProvider wrapper. This framework provides a theme for all components of React within itself via the Context API. All styled-components will have access to the given theme in the rendering tree, even though they are deeply multi-level. As we continue this tutorial, we will investigate the thematic features of modeled components more deeply SETTING UP
1. CREATE THE FILE STRUCTURECreating a folder and inserting within it three empty text files: one with.html, one with.css, and one with.js. Also, create a folder of images for the photos you wish to view on the website.JQuery also makes use of our "dark mode in CSS" demo. In the example, we are going to add the script right from the Cloudflare CDN to the HTML file so that it is always up to date. If you like, however, you can download and add the jQuery library as a local.js file as well.Here's how the file structure will look before coding begins:
- dark-mode-css/ - images/ - cake.jpg - index.html - script.js - style.css
2. MARK UP THE HTMLAdd the dark-mode switch to the top of the page in the HTML. Then create a < h1 > title tag, and a semantic < article > tag for the page's content. Finally, just before the < /body > tag closes add the two < script > tags.Please note that before the custom script you are adding the jQuery library so it can use its functionalities. The style.css file will go into the page's < head > section.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Demo | Dark Mode in CSS</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="switch">Dark mode: <span class="inner-switch">OFF</span> </div> <h1 class="title">The Best Recipes of All Time</h1> <article> <h1>Raspberry Cake</h1> <p><small>Created with Cupcake Ipsum</small></p> <p>...</p> <img src="images/cake.jpg"> <p>...</p> </article> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="script.js"></script> </body> </html>
3. CREATE THE CSS FOR THE LIGHT MODEFirst, let's build the CSS for light mode, since this is the page's default state. The following CSS makes use of a column-based flexbox style that allows you to easily place elements on the page, specifically the.switch class that handles the dark mode toggle wrapper and the < img > elements.
body { font-family: sans-serif; font-size: 1.125rem; display: flex; flex-direction: column; max-width: 50rem; margin: 0 auto; padding: 0 0.9375rem; } small { font-style: italic; } article { display: flex; flex-direction: column; } img { max-width: 100%; display: block; align-self: center; } .switch { align-self: flex-end; margin: 0.9375rem; } .inner-switch { display: inline-block; cursor: pointer; border: 1px solid #555; border-radius: 1.25rem; width: 3.125rem; text-align: center; font-size: 1rem; padding: 0.1875rem; margin-left: 0.3125rem; }
The display: flex; rule applied to the tag allows the align-self to be used: flex-end; rule over the dark mode turn. The align-self CSS property aligns individual flex elements along the cross-axis (which is the left-to-right axis when a column is set to flex-direction).In this way, the move is located automatically to the top right corner of the flex container — for all viewport sizes. .switch is a full-width layout row due to the flexbox, and its height does not fall at smaller screen sizes either.Similarly, the display: flex; and flex-direction: column; rules added to the < article > tag allow align-self to be used: center; rule on all images inside the post. As a result, all the images can be conveniently focused without adding extra elements to the HTML, only for positioning purposes. 4. ADD THE SWITCH FUNCTIONALITY WITH JQUERYThe.js script file provides the toggle switch feature. Therefore, the dark mode is activated when the user clicks the toggle and the mark on the switch switches to "ON." And if, when the page is in dark mode, the user clicks the toggle, the light mode is added and the mark switches to "OFF."
$( ".inner-switch" ).on("click", function() { if( $( "body" ).hasClass( "dark" )) { $( "body" ).removeClass( "dark" ); $( ".inner-switch" ).text( "OFF" ); } else { $( "body" ).addClass( "dark" ); $( ".inner-switch" ).text( "ON" ); } });
The script above makes use of the following jQuery functions:·
on(“click”, function() {…})
is an event handler that triggers the action inside the function when the user clicks the .inner-switch element,·
hasClass()
checks if the .dark class is assigned to the .inner-switch element or not (this is based on the state of the toggle),·
removeClass()
removes the .dark class from the HTML when the user switches to light mode,·
addClass()
adds the .dark class to the HTML when the user switches to dark mode,·
text()
sets the text of the label on the switch — it’s either “OFF” or “ON”.· 5. ADD THE CSS FOR THE DARK MODEThe last thing you need to do is to define those styles for the.dark class that the jQuery script above added to the HTML when dark mode is turned on. In addition to the.dark class, apply the dark mode theme to both its direct and indirect children using the.dark * universal CSS selector.
.dark, .dark * { background-color: #222; color: #e6e6e6; border-color: #e6e6e6; }
The CSS belonging to the.dark class goes to the file ending with style.css. This is because CSS (= Cascading Style Sheets) is cascading in nature. The cascade may thus bypass the colors all over the page without bumping into specificity or other probelms.You can also create a separate dark.css file for the dark mode styles if you are creating a more complex website. In this case, be careful that you always add the unique dark.css in the < head > section of the HTML after the generic style.css file, so that the cascade will work properly.
CREATING THEME-TOGGLING FUNCTIONALITY1. Add HTML:Using any item that should store the content for which you want the interface toggle. In our case, for simplicity we'll use < body >:
Example
<body>
Add CSS:Design the item < body > and build a toggle class in.dark-mode:
Example
body { padding: 25px; background-color: white; color: black; font-size: 25px; } .dark-mode { background-color: black; color: white; }
3) Add JavaScript:Get the < body > item and switch between the class of dark-mode:
Example
function myFunction() { var element = document.body; element.classList.toggle("dark-mode"); }
ConclusionDark mode is increasingly becoming a choice for the consumer, and it is much easier to integrate it into a web app by using the Theme Provider theme wrapper in styled components. Go ahead and play with styled-components as you implement dark mode; you could add icons instead of a button.
As a reputed Software Solutions Developer we have expertise in providing dedicated remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to
get in touch with us!
0 notes
Photo

13 Best Help-Desk Plugins for WordPress (and 5 Free Plugins)
Are you looking for a reliable WordPress help-desk plugin? Solving issues related to your products on time will lead to happy clients and customers. In this post, I'll show you some of the best WordPress plugins for creating and running a help desk.
Why Do You Need a Help Desk?
A professional help desk will help you address your customers questions and technical problems in a fast, reliable, and timely manner.
It will help you organise customer complaints and queries in the order they come in, assign them a ticket, and finally redirect them to the right department for help.
It will also help you look up customer queries using a ticket number so you can inform customers about the progress of their queries.
A well run help desk will leave your customers satisfied, which will in turn translate into repeat business.
Top Selling WordPress Help Desk Plugins for 2020 on CodeCanyon
CodeCanyon is the world's premier marketplace for professional WordPress themes and plugins. Grab one of these WordPress help desk plugins and transform the way your give technical support to your customers.
10 Best WordPress Help Desk Plugins
At CodeCanyon you will find many help desk plugins for your WordPress website.
Lets have a look at the best of the best.
1. Knowledge Base
The Knowledge Base WordPress plugin helps you build a customer self-service help desk in minutes. Create resources with helpful articles and answer frequently asked questions. Users of this plugin create customer support centers, FAQs, product or service documentation, internal company documentation, wikis, and much more.
2. TotalDesk
TotalDesk is a comprehensive,, all-in-one help desk solution for WordPress. Features include: ticket and notification system, live chat, knowledge base, and reports.
3. MinervaKB Knowledge Base
The MinervaKB knowledge base plugin comes with a powerful WordPress FAQ module with instant filtering and categories. It is easy to customize and comes with unlimited design options. You can restrict content and show teasers. You can also integrate top plugins like WPML, Elementor, and Visual Composer.
4. FAST: Support Ticket Plugin
FAST is a professional support ticket system that is easy for your customers to use. It will give you and your team up-to-the-minute updates using email and Slack notifications.
The makers of FAST use it themselves to provide support tickets for their 20,000 plus customers on ThemeForest and CodeCanyon. It’s so fast, it’s like chatting to your customers!
5. Helpy
With Helpy you can create a knowledge base that is accessible only by your customers. In addition, you can create an internal wiki for your team or a Wikipedia-like website with front-end editing and publishing capabilities. And finally you can create documentation for your WordPress websites. The documentation can be technical documentation or product documentation for your end users.
6. Atlas Knowledge Base
The Atlas knowledge base plugin helps you create a self-serve online library of information about a product, service, department, or topic, helping you to reduce your support volume and increase customer satisfaction. Atlas comes with a modern look and feel and two beautifully designed, mobile-ready themes to match your brand.
7. AI Chat Support Board
The Support Board plugin helps you automate your customers’ communication with artificial intelligence-driven bots and a chat system integrated with the most-used platforms. Save time and use the software you already know and love. Communicate with your customers directly in Slack. Connect Dialogflow and use rich messages on the fly.
8. WooCommerce Support Ticket System
The WooCommerce Support Ticket System seamlessly integrates into your WooCommerce installation, adding a system to manage user and order support tickets. In this way the shop admin can easily track and give support for orders and users' issues!
Note: This plugin, like the latest versions of WordPress, requires PHP version 5.5 or higher.
9. Sabai Discuss
Sabai Discuss is an ideal tool for building a knowledge base and a help desk portal for your WordPress website. You can also use it to build a community-driven question-and-answer website similar to Yahoo Answers and Stack Overflow.
10. Knowledgebase X
Knowledgebase X is an advanced WordPress knowledge base plugin with FAQ, glossary and AI-powered chat bot help desk features all in one. It easily allows you to build a robust self-service support system that will help significantly reduce live support time. It supports file attachment, alternative questions for articles, upvotes, downvotes, and a lot more!
The chat bot can be integrated with Google’s DialogFlow AI and NLP engine.
11. Multi Helpdesk Pro
Multi Helpdesk Pro is perfect for those entrepreneurs who want to host their own support ticket system service, where companies all over the world can host their help desks. With this plugin, you could build a business of hosting and supporting help desks.Try out the support ticket system business model!
12. Pinky Chat
Pinky Chat is a live chat application and help desk software for your websites. As a faster way to quickly handle your customer service, you can talk to your customer in real-time over the web. Additionally you can track analytics of your website, visitor’s path, and geolocation details. Finally, the live chat widget works with any website: static HTML websites, WordPress, OpenCart, Joomla, Drupal, or PHP scripts.
13. Forym
Forym has many powerful features that allow you to create a professional looking help desk or forum with ease! Users can ask and receive answers from fellow users.
The forum is created to work on the front-end of your website but admins are able to manage all forums, topics, replies, categories and tags from the admin area as well.
5 Free WordPress Help Desk Plugins
In case your current budget does not allow you to buy one of these premium help desk plugins, I have collected a list of five of the best free help desk plugins available.
1. SupportCandy
SupportCandy adds the features of a complete help desk ticket system to WordPress. With this easy to use and easy to configure plugin, you get simplicity, functionality and extendability.
2. JS Help Desk
JS Help Desk is a trusted open source ticket system. JS Help Desk is a simple, easy to use, web-based customer support system. Users and guests can create tickets from the front-end. JS Help Desk comes packed with a lot of features—more even than some expensive (and complex) support ticket systems. The best part is, it completely free.
3. WordPress Advanced Ticket System, Elite Support Desk
WordPress Advanced Ticket System is a complete support ticket system for WordPress. This allows users to submit tickets to report problems and set the status, priority, product, and type of each ticket. In this plugin, registered users can submit a ticket through the admin and unregistered users do ticket submission through via the shared guest user feature.
4. WSDesk
WSDesk allows you to turn all your customer complaints turn into trackable tickets so you manage your customer queries seamlessly.
WSDesk comes with all the basic features required to set up an online-support: ticket creation & management, email piping, unlimited agents, unlimited tickets, customizable email reply, complete ticket history, file attachment to tickets and much more!
5. KB Support
KB Support is the ultimate WordPress plugin for providing support and helpdesk services to your customers.
Enriched with features, you can be sure that right from activation, KB Support will provide the perfect help desk solution for your agents to support your customers.
The built-in knowledge base allows customers to find solutions to their issues during the ticket submission process, reducing the overall number of support queries received by your help desk.
Before Setting Up a Help Desk
Carry out an honest appraisal of your internal and external communications, define your goals, then choose what plugin that will work for you. The aim should always be to provide the best support to your customers.
Appraisal of Internal Communication
How are your internal communication processes?
What tools do you use to communicate internally?
Where do they succeed and where do they fail?
How do you assign tasks to each member of the help desk team?
How can you improve this process?
Appraisal of External Communication
Take a close look at your communication channels with customers.
What channels are available for customers to reach you with their problems?
How do you communicate with your customers about their queries?
Be honest when assessing how effective these channels are.
Define Your Help Desk Goals
First, think about your help desk team.
How many help desk staff do you need?
How do you want to organize your help desk team?
What problems do you want to solve?
Then you can document and define your help desk processes and workflows.
Make a list of all technical issues you anticipate.
Build detailed help desk workflow.
Identify repetitive help desk tasks that can automate.
Have a detailed knowledge base for internal use by help desk staff.
Create a knowledge base for problems customers can solve by themselves.
Identify metrics you will use to define and track success.
Things to Consider When Choosing a Help Desk Plugin
Budget
See what each help desk software fits within your budget and offers must-have features. Also make sure you look at free software. Free does not necessarily mean limited!
Features
Know exactly what features your want. That way you can leave out systems that will not serve your needs. The most important is to understand how detailed you want your ticketing system to be and how much control you want to have. Always make sure your ticket system can integrate with email and can also send SMS for customers that prefer it.
Customization
The ability to customizing the help desk system to the look of your brand is important. You should be able to personalise all templates that the system comes with. This means adding your business name, logo, and colors on the tickets and emails etc.
Ease of Use
The point of a help desk is to make processes faster and easier. If the system you choose is difficult to use it will slow down your help desk agents and you will not deliver fast, reliable service to your customers.
Web Interface
Allows customers to log into the service portal and check the progress of their tickets. This front-end interface should look good to build confidence in your product.
Security
There is a lot of customer data goes back and forth through your ticketing system. Make sure the system you are considering uses strong encryption.
Launch Your Help Desk Today With a Great WordPress Help Desk Plugin
You can purchase one of these high-quality WordPress help desk plugins on CodeCanyon and create a fantastic technical support experience for your customers.
The following articles by my colleagues will help you discover more options to help create the help desk that fits the needs of your business and customers.
WordPress Themes
16 Best Knowledge Base & Wiki Themes, Plugins and Templates
Brenda Barron
Workflow
Email Isn't Working. How to Use Computers to Support Customers
Johnny Winter
PHP
14 Best PHP Help-Desk Scripts and 5 Free Options
Franc Lucas
by Franc Lucas via Envato Tuts+ Code https://ift.tt/2MIxPEE
0 notes
Text
Learn React Basics in 10 Minutes
If you want to learn the basics of React in the time it takes you to drink a cup of coffee, this post is for you.
This article aims to provide a beginner-friendly introduction to React, what it is and why we need it. It assumes you have some understanding of basic JavaScript.
We will discuss some of its basic concepts and go over what you can build with React.
We will also discuss some code but the overall goal is to gain an intuitive understanding of what React is all about so that you get comfortable with the basics.
What is React?
Developed by Facebook in 2011, React has quickly become one of the most widely used JavaScript libraries. According to HackerRank, 30% of employers look for developers who know React but only about half of the applicants actually have the required knowledge.
Clearly, React is in high demand in the job market.
So what exactly is React?
React is an efficient and flexible JavaScript library for building user interfaces (with itself written using JavaScript). It breaks down complex UIs in the form of small, isolated code called “components”. By using these components, React only concerns itself with what you see on the front page of a website.
A calculator app that can be split into React components.
Components are independent and reusable. They can either be Javascript functions or classes. Either way, they both return a piece of code that represents part of a web page.
Here’s an example of a function component that renders a <h2> element onto the page:
function Name() { return <h2>Hi, my name is Joe!</h2>; }
And here is a class component doing the same rendering:
class Person extends React.Component { render() { return <h2>Hi again from Joe!</h2>; } }
Using a class component takes slightly more effort in that you have to extend React.Component (part of the React library) while a function component is mostly plain JavaScript. However, class components provide certain critical functionalities that function components lack (see Functional vs Class-Components in React).
You may have noticed that there is a strange mixture of HTML and JavaScript inside each component. React actually uses a language called JSX that allows HTML to be mixed with Javascript.
Not only can you use JSX to return pre-defined HTML elements, you can also create your own. For example, instead of rendering <h2> elements directly in the class component, you can render the functional component which returns the same thing:
class Person extends React.Component { render() { return <Name />; } }
Note the self-closing ‘/>’ of the component.
The power of React starts to become more evident as you can imagine rendering many simple components to form a more complex one.
To build a page, we can call these components in a certain order, use the results they return, and display them to the user.
Why Choose React Over Vanilla JavaScript?
Being able to break down complex UIs through the use of components obviously gives React an edge over vanilla JavaScript (plain JS without any external libraries or frameworks), but what else can React do that places it in such high demand among employers?
Let’s take a look at the differences between how React and vanilla JS handles things.
In the previous section, we discussed how React uses components to render UIs. We did not delve into what was happening on the HTML side of things. It may be surprising to learn that the HTML code that pairs with React is really simple:
<div id="root"></div>
It is usually just a <div> element with an id that serves as a container for a React app. When React renders its components, it will look for this id to render to. The page is empty before this rendering.
Vanilla JS on the other hand defines the initial UI right in the HTML.
In addition, vanilla JS takes care of functionality while HTML takes care of displaying content (markup).
In the earlier days of the web the separation of functionality and markup sounded logical as apps were simpler. However, as complexity grew so do the headaches of maintaining large pieces of JS code.
JS code that updates a piece of HTML can be spread across several files, and the developers may have a hard time keeping track of where the code came from. They have to keep things straight in their heads of all the interactions between the code that resides in different files.
React sorts the code into components, where each component maintains all the code needed to both display and update the UI.
Updating the UI requires updating the DOM, or document object model (see DOM Manipulation Using JavaScript). This is where React truly shines.
If you want to access the DOM in vanilla JS, you have to first find it before it can be used. React stores the data in regular JS variables and maintains its own virtual DOM.
If you want to then update the DOM in vanilla JS, you have to locate the appropriate node then manually append or remove elements. React automatically updates the UI based on the application state, which we will discuss in more detail in the next section.
So the primary reason why we may want to use React over vanilla JS can be summarized in one word: simplicity.
With vanilla JS, it’s easy to get lost in a maze of DOM searches and updates. React forces you to break down your app into components which produces more maintainable code.
Thus, for complex apps you will definitely want to learn React.
Basic React Concepts
We have already discussed how React uses components to break down complex UIs and JSX to render those components.
In this section we will talk about some more fundamental concepts of React.
State
As mentioned previously, React updates the UI based on the application state. This state is actually stored as a property of a React class component:
class Counter extends React.Component { state = { value: 0 }; }
Suppose we have a counter and 2 buttons that either increment or decrement. The value of the counter is rendered onto the page through JSX.
The display counter value is based on the state and we change the state by clicking one of the buttons. Vanilla JS treats a button click as an event and so does React. When such an event occurs, we will call functions that either increment or decrement the counter based on the button clicked. These functions have the code that changes the component state.
Here’s an example of such a counter:
class Counter extends React.Component { state = { value: 0 }; handleIncrement= () => { this.setState(state => { value: state.value + 1 }); }; handleDecrement= () => { this.setState(state => { value: state.value - 1 }); }; render() { return ( <div> <h2>{this.state.value}</h2> <button onClick={this.handleDecrement}>Decrement</button> <button onClick={this.handleIncrement}>Increment</button> </div> ); } };
We updated the state by calling setState in each of the functions handling a button click. The counter displayed on the page will update in real time. Thus, React gets its name because it reacts to state changes.
In short, React automatically monitors every component state for changes and updates the DOM appropriately.
Props
We can use props (short for "properties") to allow components to talk to each other.
Suppose the counter in our previous example represents the quantity of a product a customer wishes to purchase. The store wants to place a limit of 2 products purchased per customer. At checkout, we want to display an appropriate message if the customer tries to purchase more than 2.
Here’s how we may do it with props:
const Display = (props) => { let message; if(props.number>2){ message = ‘You’re limited to purchasing 2 max!’; }else{ message = ‘All’s good.’; } return( <p>message</p> ); }; class Timer extends React.Component { state = { quantity: 0 } //...code for handling button clicking, updating state, etc. render(){ return( <Display number = {this.state.quantity} /> //...code for other components ); } };
We create a functional component called Display and pass props as a parameter. When we render this component, we pass to it number as an attribute set to the quantity of the product a customer wants to purchase. This is similar to setting an attribute of an HTML tag. We call this value with props.number in Display to determine what message to return.
Component Lifecycle
As React updates the DOM based on component states, special methods called lifecycle methods exist to provide opportunities to perform actions at specific points in the lifecycle of a component.
They allow you to catch components at a certain point in time to call appropriate functions. These points of time can be before components are rendered, after they are updated, etc. You may want to explore a component’s lifecycle methods.
To see lifecycle methods in action, you can check out this Pomodoro Clock I made.
The clock timer is initially set to the session length. When the session timer counts down to zero, the timer needs to switch to the break length and start counting down from there.
Since the timer is a component, I used the lifecycle method componentDidUpdate within my main class component to handle any changes with handleChange():
componentDidUpdate() { this.handleChange(); }
You can think of lifecycle methods as adding event listeners in vanilla JS to a React component.
What Can You Build with React?
So now you have a basic understanding of React, what can you build with it?
We already mentioned in the beginning of this post that Facebook developed React in 2011, so naturally the Facebook platform is based on React. Other famous apps that either completely or partially use React include Instagram, Netflix, and Whatsapp.
But as beginners of React, we are not looking to immediately build the next Facebook so here’s a list of 10 React Starter Project Ideas to Get You Coding.
If you want to learn more about web development and check out some examples of beginner-friendly React projects, visit my blog at 1000 Mile World.
Thanks for reading and happy coding!
via freeCodeCamp.org https://ift.tt/2UicncL
0 notes
Text
Rewriting the Beginner's Guide to SEO
Posted by BritneyMuller
(function($) { // code using $ as alias to jQuery $(function() { // Hide the hypotext content. $('.hypotext-content').hide(); // When a hypotext link is clicked. $('a.hypotext.closed').click(function (e) { // custom handling here e.preventDefault(); // Create the class reference from the rel value. var id = '.' + $(this).attr('rel'); // If the content is hidden, show it now. if ( $(id).css('display') == 'none' ) { $(id).show('slow'); if (jQuery.ui) { // UI loaded $(id).effect("highlight", {}, 1000); } } // If the content is shown, hide it now. else { $(id).hide('slow'); } }); // If we have a hash value in the url. if (window.location.hash) { // If the anchor is within a hypotext block, expand it, by clicking the // relevant link. console.log(window.location.hash); var anchor = $(window.location.hash); var hypotextLink = $('#' + anchor.parents('.hypotext-content').attr('rel')); console.log(hypotextLink); hypotextLink.click(); // Wait until the content has expanded before jumping to anchor. //$.delay(1000); setTimeout(function(){ scrollToAnchor(window.location.hash); }, 1000); } }); function scrollToAnchor(id) { var anchor = $(id); $('html,body').animate({scrollTop: anchor.offset().top},'slow'); } })(jQuery); .hypotext-content { position: relative; padding: 10px; margin: 10px 0; border-right: 5px solid; } a.hypotext { border-bottom: 1px solid; } .hypotext-content .close:before { content: "close"; font-size: 0.7em; margin-right: 5px; border-bottom: 1px solid; } a.hypotext.close { display: block; position: absolute; right: 0; top: 0; line-height: 1em; border: none; }
Many of you reading likely cut your teeth on Moz’s Beginner’s Guide to SEO. Since it was launched, it's easily been our top-performing piece of content:
Most months see 100k+ views (the reverse plateau in 2013 is when we changed domains).
While Moz’s Beginner's Guide to SEO still gets well over 100k views a month, the current guide itself is fairly outdated. This big update has been on my personal to-do list since I started at Moz, and we need to get it right because — let’s get real — you all deserve a bad-ass SEO 101 resource!
However, updating the guide is no easy feat. Thankfully, I have the help of my fellow Mozzers. Our content team has been a collective voice of reason, wisdom, and organization throughout this process and has kept this train on its tracks.
Despite the effort we've put into this already, it felt like something was missing: your input! We're writing this guide to be a go-to resource for all of you (and everyone who follows in your footsteps), and want to make sure that we're including everything that today's SEOs need to know. You all have a better sense of that than anyone else.
So, in order to deliver the best possible update, I'm seeking your help.
This is similar to the way Rand did it back in 2007. And upon re-reading your many "more examples" requests, we’ve continued to integrate more examples throughout.
The plan:
Over the next 6–8 weeks, I’ll be updating sections of the Beginner's Guide and posting them, one by one, on the blog.
I'll solicit feedback from you incredible people and implement top suggestions.
The guide will be reformatted/redesigned, and I'll 301 all of the blog entries that will be created over the next few weeks to the final version.
It's going to remain 100% free to everyone — no registration required, no premium membership necessary.
To kick things off, here’s the revised outline for the Beginner’s Guide to SEO:
Click each chapter's description to expand the section for more detail.
Chapter 1: SEO 101
What is it, and why is it important? ↓
What is SEO?
Why invest in SEO?
Do I really need SEO?
Should I hire an SEO professional, consultant, or agency?
Search engine basics:
Google Webmaster Guidelines basic principles
Bing Webmaster Guidelines basic principles
Guidelines for representing your business on Google
Fulfilling user intent
Know your SEO goals
Chapter 2: Crawlers & Indexing
First, you need to show up. ↓
How do search engines work?
Crawling & indexing
Determining relevance
Links
Personalization
How search engines make an index
Googlebot
Indexable content
Crawlable link structure
Links
Alt text
Types of media that Google crawls
Local business listings
Common crawling and indexing problems
Online forms
Blocking crawlers
Search forms
Duplicate content
Non-text content
Tools to ensure proper crawl & indexing
Google Search Console
Moz Pro Site Crawl
Screaming Frog
Deep Crawl
How search engines order results
200+ ranking factors
RankBrain
Inbound links
On-page content: Fulfilling a searcher’s query
PageRank
Domain Authority
Structured markup: Schema
Engagement
Domain, subdomain, & page-level signals
Content relevance
Searcher proximity
Reviews
Business citation spread and consistency
SERP features
Rich snippets
Paid results
Universal results
Featured snippets
People Also Ask boxes
Knowledge Graph
Local Pack
Carousels
Chapter 3: Keyword Research
Next, know what to say and how to say it. ↓
How to judge the value of a keyword
The search demand curve
Fat head
Chunky middle
Long tail
Four types of searches:
Transactional queries
Informational queries
Navigational queries
Commercial investigation
Fulfilling user intent
Keyword research tools:
Google Keyword Planner
Moz Keyword Explorer
Google Trends
AnswerThePublic
SpyFu
SEMRush
Keyword difficulty
Keyword abuse
Content strategy {link to the Beginner’s Guide to Content Marketing}
Chapter 4: On-Page SEO
Next, structure your message to resonate and get it published. ↓
Keyword usage and targeting
Keyword stuffing
Page titles:
Unique to each page
Accurate
Be mindful of length
Naturally include keywords
Include branding
Meta data/Head section:
Meta title
Meta description
Meta keywords tag
No longer a ranking signal
Meta robots
Meta descriptions:
Unique to each page
Accurate
Compelling
Naturally include keywords
Heading tags:
Subtitles
Summary
Accurate
Use in order
Call-to-action (CTA)
Clear CTAs on all primary pages
Help guide visitors through your conversion funnels
Image optimization
Compress file size
File names
Alt attribute
Image titles
Captioning
Avoid text in an image
Video optimization
Transcription
Thumbnail
Length
"~3mo to YouTube" method
Anchor text
Descriptive
Succinct
Helps readers
URL best practices
Shorter is better
Unique and accurate
Naturally include keywords
Go static
Use hyphens
Avoid unsafe characters
Structured data
Microdata
RFDa
JSON-LD
Schema
Social markup
Twitter Cards markup
Facebook Open Graph tags
Pinterest Rich Pins
Structured data types
Breadcrumbs
Reviews
Events
Business information
People
Mobile apps
Recipes
Media content
Contact data
Email markup
Mobile usability
Beyond responsive design
Accelerated Mobile Pages (AMP)
Progressive Web Apps (PWAs)
Google mobile-friendly test
Bing mobile-friendly test
Local SEO
Business citations
Entity authority
Local relevance
Complete NAP on primary pages
Low-value pages
Chapter 5: Technical SEO
Next, translate your site into Google's language. ↓
Internal linking
Link positioning
Anchor links
Common search engine protocols
Sitemaps
Mobile
News
Image
Video
XML
RSS
TXT
Robots
Robots.txt
Disallow
Sitemap
Crawl Delay
X-robots
Meta robots
Index/noindex
Follow/nofollow
Noimageindex
None
Noarchive
Nocache
No archive
No snippet
Noodp/noydir
Log file analysis
Site speed
HTTP/2
Crawl errors
Duplicate content
Canonicalization
Pagination
What is the DOM?
Critical rendering path
Help robots find the most important code first
Hreflang/Targeting multiple languages
Chrome DevTools
Technical site audit checklist
Chapter 6: Establishing Authority
Finally, turn up the volume. ↓
Link signals
Global popularity
Local/topic-specific popularity
Freshness
Social sharing
Anchor text
Trustworthiness
Trust Rank
Number of links on a page
Domain Authority
Page Authority
MozRank
Competitive backlinks
Backlink analysis
The power of social sharing
Tapping into influencers
Expanding your reach
Types of link building
Natural link building
Manual link building
Self-created
Six popular link building strategies
Create content that inspires sharing and natural links
Ego-bait influencers
Broken link building
Refurbish valuable content on external platforms
Get your customers/partners to link to you
Local community involvement
Manipulative link building
Reciprocal link exchanges
Link schemes
Paid links
Low-quality directory links
Tiered link building
Negative SEO
Disavow
Reviews
Establishing trust
Asking for reviews
Managing reviews
Avoiding spam practices
Chapter 7: Measuring and Tracking SEO
Pivot based on what's working. ↓
KPIs
Conversions
Event goals
Signups
Engagement
GMB Insights:
Click-to-call
Click-for-directions
Beacons
Which pages have the highest exit percentage? Why?
Which referrals are sending you the most qualified traffic?
Pivot!
Search engine tools:
Google Search Console
Bing Webmaster Tools
GMB Insights
Appendix A: Glossary of Terms
Appendix B: List of Additional Resources
Appendix C: Contributors & Credits
What did you struggle with most when you were first learning about SEO? What would you have benefited from understanding from the get-go?
Are we missing anything? Any section you wish wouldn't be included in the updated Beginner's Guide?
Thanks in advance for contributing.
Sign up for The Moz Top 10, a semimonthly mailer updating you on the top ten hottest pieces of SEO news, tips, and rad links uncovered by the Moz team. Think of it as your exclusive digest of stuff you don't have time to hunt down but want to read!
from The Moz Blog http://ift.tt/2AIAGpW via IFTTT
2 notes
·
View notes
Text
300+ TOP CherryPy Interview Questions and Answers
CherryPy Interview Questions for freshers experienced :-
1. What is CherryPy? CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library. CherryPy uses Python’s strengths as a dynamic language to model and bind HTTP protocol into an API. It is one of the oldest web frameworks for Python, which provides clean interface and reliable platform. 2. Why we use CherryPy? CherryPy has following strength: Simplicity: It makes less line to code for project development. Open source: CherryPy framework is an open source. Power: It provides powerful tools and plugins which make to develop world-class application. Community Help: It provide full support on different questions and answers by devoted community. Deployment: CherryPy has its own production-ready HTTP server which make cost effective to host application. 3. What are the installation set up for CherryPy? There are various installation set up are available for CherryPy in package form. Using Tarball Using easyinstall Using Subversion 4. What are the basic requirements for CherryPy installation? These are the basic requirement for CherryPy installation: Python with version 2.0 or above CherryPy 3.0 5. What is web server in CherryPy? The web server acts as the gateway to the application which handles all the requests and response. Following command is used to start web server: cherryPy.server.quickstart() 6. What does internal engine in CherryPy? Following activities are performed by internal engine in CherryPy. Creation and management of request and response objects. Controlling and managing the CherryPy objects. 7. Define multithreaded application server? CherryPy provide multithreaded environment to gets and sets a value into the CherryPy namespace. 8. What is CherryPy Toolbox? It is a built-in tool which offers a single interface to call the CherryPy library. This tool is used in three different ways: From configuration settings As a Python decorator or via special _cp_config attribute of a page handler. As a Python callable that can be applied from within any function 9. What is Basic Authentication Tool? The purpose of this tool is to provide basic authentication to application. This tool uses the following arguments: realm users encrypt 10. What is Caching Tool? This tool is used to provide memory caching to CherryPy generated content. This tool uses the following arguments: invalid_methods cache_Class
CherryPy Interview Questions 11. What is Decoding Tool? The purpose of this tool is to decode the incoming request parameters. Following arguments are used in this tool: encoding Default_encoding 12. Define CherryPy Web Services? A web services is a web based components. It helps to exchange data between applications. There are various types of web service available: REST (RESTful) SOAP etc 13. What are the components of CherryPy? CherryPy has the following three components: cherrypy.engine: It controls prcess startup and event handling. cherrypy.server: It controls and configures server (HTTP server). cherrypy.tools: It is like a toolbox that is orthogonal to execute a HTTP request. 14. What is Atom Publication Protocol (APP)? APP is an application level protocol. It allows the publishing and editing of web resources. It also performs set of operations between APP service and user-agent. It uses Atom XML-document format for message unit between APP server and client. 15. What is Kid template? Kid is a simple template engine written in Python. While creating the template for first time, Kid creates a Python module which can be works as a cached version of the template. Kid template includes the name of the template to be processed which is mandatory. 16. What is Cherrypy configuration? The framework comes with its own configuration system allowing you to parameterize the HTTP server. The settings for the configuration can be stored either in a text file with syntax close to the INI format or as a complete Python dictionary. To configure the CherryPy server instance, the developer needs to use the global section of the settings. global_conf = { 'global': { 'server.socket_host': 'localhost', 'server.socket_port': 8080, }, } application_conf = { '/style.css': { 'tools.staticfile.on': True, 'tools.staticfile.filename': os.path.join(_curdir, 'style.css'), } } This could be represented in a file like this: server.socket_host = "localhost" server.socket_port = 8080 tools.staticfile.on = True tools.staticfile.filename = "/full/path/to.style.css" 17. How to applying Ajax to the application? Consider the application which includes a folder named “media” with index.html and Jquery plugin, and a file with AJAX implementation. Let us consider the name of the file as “ajax_app.py” ajax_app.py import cherrypy import webbrowser import os import simplejson import sys MEDIA_DIR = os.path.join(os.path.abspath("."), u"media") class AjaxApp(object): @cherrypy.expose def index(self): return open(os.path.join(MEDIA_DIR, u'index.html')) @cherrypy.expose def submit(self, name): cherrypy.response.headers = 'application/json' return simplejson.dumps(dict(title="Hello, %s" % name)) config = {'/media': {'tools.staticdir.on': True, 'tools.staticdir.dir': MEDIA_DIR,} } def open_page(): webbrowser.open("http://127.0.0.1:8080/") cherrypy.engine.subscribe('start', open_page) cherrypy.tree.mount(AjaxApp(), '/', config=config) cherrypy.engine.start() The class “AjaxApp” redirects to the web page of “index.html”, which is included in the media folder. AJAX with jQuery and cherrypy $(function() { // When the testform is submitted... $("#formtest").submit(function() { // post the form values via AJAX... $.post('/submit', {name: $("#name").val()}, function(data) { // and set the title with the result $("#title").html(data) ; }); return false ; }); });
What's your name?
Name: The function for AJAX is included within tags. 18. What is rest interface through cherrypy? RESTful web service implements each section of CherryPy architecture with the help of the following − Authentication Authorization Structure Encapsulation Error Handling Authentication: Authentication helps in validating the users with whom we are interacting. CherryPy includes tools to handle each authentication method. def authenticate(): if not hasattr(cherrypy.request, 'user') or cherrypy.request.user is None: # cherrypy.request.authorized = False # This only authenticates. Authz must be handled separately. cherrypy.request.unauthorized_reasons = cherrypy.request.authorization_queries = cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate, priority=10) The above function authenticate() will help to validate the existence of the clients or users. The built-in tools help to complete the process in a systematic way. Authorization: Authorization helps in maintaining the sanity of the process via URI. The process also helps in morphing objects by user token leads. def authorize_all(): cherrypy.request.authorized = 'authorize_all' cherrypy.tools.authorize_all = cherrypy.Tool('before_handler', authorize_all, priority=11) def is_authorized(): if not cherrypy.request.authorized: raise cherrypy.HTTPError("403 Forbidden", ','.join(cherrypy.request.unauthorized_reasons)) cherrypy.tools.is_authorized = cherrypy.Tool('before_handler', is_authorized, priority = 49) cherrypy.config.update({ 'tools.is_authorized.on': True, 'tools.authorize_all.on': True }) The built-in tools of authorization help in handling the routines in a systematic way, as mentioned in the previous example. 19. What is Cherrypy web services? A web service is a set of web-based components that helps in the exchange of data between the application or systems which also includes open protocols and standards. It can be published, used and found on the web. 20. What is decoding tool? The purpose of this tool is to decode the incoming request parameters. Arguments This tool uses the following arguments: encoding---- None--- It looks for the content-type header Default_encoding--- "UTF-8"--- Default encoding to be used when none is provided or found. CherryPy Questions and Answers Pdf Download Read the full article
0 notes
Text
The Ultimate Guide To Building Scalable Web Scrapers With Scrapy
The Ultimate Guide To Building Scalable Web Scrapers With Scrapy
Daniel Ni
2019-07-16T14:30:59+02:002019-07-16T13:06:15+00:00
Web scraping is a way to grab data from websites without needing access to APIs or the website’s database. You only need access to the site’s data — as long as your browser can access the data, you will be able to scrape it.
Realistically, most of the time you could just go through a website manually and grab the data ‘by hand’ using copy and paste, but in a lot of cases that would take you many hours of manual work, which could end up costing you a lot more than the data is worth, especially if you’ve hired someone to do the task for you. Why hire someone to work at 1–2 minutes per query when you can get a program to perform a query automatically every few seconds?
For example, let’s say that you wish to compile a list of the Oscar winners for best picture, along with their director, starring actors, release date, and run time. Using Google, you can see there are several sites that will list these movies by name, and maybe some additional information, but generally you’ll have to follow through with links to capture all the information you want.
Obviously, it would be impractical and time-consuming to go through every link from 1927 through to today and manually try to find the information through each page. With web scraping, we just need to find a website with pages that have all this information, and then point our program in the right direction with the right instructions.
In this tutorial, we will use Wikipedia as our website as it contains all the information we need and then use Scrapy on Python as a tool to scrape our information.
A few caveats before we begin:
Data scraping involves increasing the server load for the site that you’re scraping, which means a higher cost for the companies hosting the site and a lower quality experience for other users of that site. The quality of the server that is running the website, the amount of data you’re trying to obtain, and the rate at which you’re sending requests to the server will moderate the effect you have on the server. Keeping this in mind, we need to make sure that we stick to a few rules.
Most sites also have a file called robots.txt in their main directory. This file sets out rules for what directories sites do not want scrapers to access. A website’s Terms & Conditions page will usually let you know what their policy on data scraping is. For example, IMDB’s conditions page has the following clause:
Robots and Screen Scraping: You may not use data mining, robots, screen scraping, or similar data gathering and extraction tools on this site, except with our express-written consent as noted below.
Before we try to obtain a website’s data we should always check out the website’s terms and robots.txt to make sure we are obtaining legal data. When building our scrapers, we also need to make sure that we do not overwhelm a server with requests that it can’t handle.
Luckily, many websites recognize the need for users to obtain data, and they make the data available through APIs. If these are available, it’s usually a much easier experience to obtain data through the API than through scraping.
Wikipedia allows data scraping, as long as the bots aren’t going ‘way too fast’, as specified in their robots.txt. They also provide downloadable datasets so people can process the data on their own machines. If we go too fast, the servers will automatically block our IP, so we’ll implement timers in order to keep within their rules.
Getting Started, Installing Relevant Libraries Using Pip
First of all, to start off, let’s install Scrapy.
Windows
Install the latest version of Python from https://www.python.org/downloads/windows/
Note: Windows users will also need Microsoft Visual C++ 14.0, which you can grab from “Microsoft Visual C++ Build Tools” over here.
You’ll also want to make sure you have the latest version of pip.
In cmd.exe, type in:
python -m pip install --upgrade pip pip install pypiwin32 pip install scrapy
This will install Scrapy and all the dependencies automatically.
Linux
First you’ll want to install all the dependencies:
In Terminal, enter:
sudo apt-get install python3 python3-dev python-pip libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev
Once that’s all installed, just type in:
pip install --upgrade pip
To make sure pip is updated, and then:
pip install scrapy
And it’s all done.
Mac
First you’ll need to make sure you have a c-compiler on your system. In Terminal, enter:
xcode-select --install
After that, install homebrew from https://brew.sh/.
Update your PATH variable so that homebrew packages are used before system packages:
echo "export PATH=/usr/local/bin:/usr/local/sbin:$PATH" >> ~/.bashrc source ~/.bashrc
Install Python:
brew install python
And then make sure everything is updated:
brew update; brew upgrade python
After that’s done, just install Scrapy using pip:
pip install Scrapy
>
Overview Of Scrapy, How The Pieces Fit Together, Parsers, Spiders, Etc
You will be writing a script called a ‘Spider’ for Scrapy to run, but don’t worry, Scrapy spiders aren’t scary at all despite their name. The only similarity Scrapy spiders and real spiders have are that they like to crawl on the web.
Inside the spider is a class that you define that tells Scrapy what to do. For example, where to start crawling, the types of requests it makes, how to follow links on pages, and how it parses data. You can even add custom functions to process data as well, before outputting back into a file.
Writing Your First Spider, Write A Simple Spider To Allow For Hands-on Learning
To start our first spider, we need to first create a Scrapy project. To do this, enter this into your command line:
scrapy startproject oscars
This will create a folder with your project.
We’ll start with a basic spider. The following code is to be entered into a python script. Open a new python script in /oscars/spiders and name it oscars_spider.py
We’ll import Scrapy.
import scrapy
We then start defining our Spider class. First, we set the name and then the domains that the spider is allowed to scrape. Finally, we tell the spider where to start scraping from.
class OscarsSpider(scrapy.Spider): name = "oscars" allowed_domains = ["en.wikipedia.org"] start_urls = ['https://en.wikipedia.org/wiki/Academy_Award_for_Best_Picture']
Next, we need a function which will capture the information that we want. For now, we’ll just grab the page title. We use CSS to find the tag which carries the title text, and then we extract it. Finally, we return the information back to Scrapy to be logged or written to a file.
def parse(self, response): data = {} data['title'] = response.css('title::text').extract() yield data
Now save the code in /oscars/spiders/oscars_spider.py
To run this spider, simply go to your command line and type:
scrapy crawl oscars
You should see an output like this:
2019-05-02 14:39:31 [scrapy.utils.log] INFO: Scrapy 1.6.0 started (bot: oscars) ... 2019-05-02 14:39:32 [scrapy.core.engine] DEBUG: Crawled (200) (referer: None) 2019-05-02 14:39:34 [scrapy.core.engine] DEBUG: Crawled (200) (referer: None) 2019-05-02 14:39:34 [scrapy.core.scraper] DEBUG: Scraped from {'title': ['Academy Award for Best Picture - Wikipedia']} 2019-05-02 14:39:34 [scrapy.core.engine] INFO: Closing spider (finished) 2019-05-02 14:39:34 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 589, 'downloader/request_count': 2, 'downloader/request_method_count/GET': 2, 'downloader/response_bytes': 74517, 'downloader/response_count': 2, 'downloader/response_status_count/200': 2, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2019, 5, 2, 7, 39, 34, 264319), 'item_scraped_count': 1, 'log_count/DEBUG': 3, 'log_count/INFO': 9, 'response_received_count': 2, 'robotstxt/request_count': 1, 'robotstxt/response_count': 1, 'robotstxt/response_status_count/200': 1, 'scheduler/dequeued': 1, 'scheduler/dequeued/memory': 1, 'scheduler/enqueued': 1, 'scheduler/enqueued/memory': 1, 'start_time': datetime.datetime(2019, 5, 2, 7, 39, 31, 431535)} 2019-05-02 14:39:34 [scrapy.core.engine] INFO: Spider closed (finished)
Congratulations, you’ve built your first basic Scrapy scraper!
Full code:
import scrapy class OscarsSpider(scrapy.Spider): name = "oscars" allowed_domains = ["en.wikipedia.org"] start_urls = ["https://en.wikipedia.org/wiki/Academy_Award_for_Best_Picture"] def parse(self, response): data = {} data['title'] = response.css('title::text').extract() yield data
Obviously, we want it to do a little bit more, so let’s look into how to use Scrapy to parse data.
First, let’s get familiar with the Scrapy shell. The Scrapy shell can help you test your code to make sure that Scrapy is grabbing the data you want.
To access the shell, enter this into your command line:
scrapy shell “https://en.wikipedia.org/wiki/Academy_Award_for_Best_Picture”
This will basically open the page that you’ve directed it to and it will let you run single lines of code. For example, you can view the raw HTML of the page by typing in:
print(response.text)
Or open the page in your default browser by typing in:
view(response)
Our goal here is to find the code that contains the information that we want. For now, let’s try to grab the movie title names only.
The easiest way to find the code we need is by opening the page in our browser and inspecting the code. In this example, I am using Chrome DevTools. Just right-click on any movie title and select ‘inspect’:
Chrome DevTools window. (Large preview)
As you can see, the Oscar winners have a yellow background while the nominees have a plain background. There’s also a link to the article about the movie title, and the links for movies end in film). Now that we know this, we can use a CSS selector to grab the data. In the Scrapy shell, type in:
response.css(r"tr[style='background:#FAEB86'] a[href*='film)']").extract()
As you can see, you now have a list of all the Oscar Best Picture Winners!
> response.css(r"tr[style='background:#FAEB86'] a[href*='film']").extract() ['<a href="/wiki/Wings_(1927_film)" title="Wings (1927 film)">Wings</a>', ... '<a href="/wiki/Green_Book_(film)" title="Green Book (film)">Green Book</a>', '<a href="/wiki/Jim_Burke_(film_producer)" title="Jim Burke (film producer)">Jim Burke</a>']
Going back to our main goal, we want a list of the Oscar winners for best picture, along with their director, starring actors, release date, and run time. To do this, we need Scrapy to grab data from each of those movie pages.
We’ll have to rewrite a few things and add a new function, but don’t worry, it’s pretty straightforward.
We’ll start by initiating the scraper the same way as before.
import scrapy, time class OscarsSpider(scrapy.Spider): name = "oscars" allowed_domains = ["en.wikipedia.org"] start_urls = ["https://en.wikipedia.org/wiki/Academy_Award_for_Best_Picture"]
But this time, two things will change. First, we’ll import time along with scrapy because we want to create a timer to restrict how fast the bot scrapes. Also, when we parse the pages the first time, we want to only get a list of the links to each title, so we can grab information off those pages instead.
def parse(self, response): for href in response.css(r"tr[style='background:#FAEB86'] a[href*='film)']::attr(href)").extract(): url = response.urljoin(href) print(url) req = scrapy.Request(url, callback=self.parse_titles) time.sleep(5) yield req
Here we make a loop to look for every link on the page that ends in film) with the yellow background in it and then we join those links together into a list of URLs, which we will send to the function parse_titles to pass further. We also slip in a timer for it to only request pages every 5 seconds. Remember, we can use the Scrapy shell to test our response.css fields to make sure we’re getting the correct data!
def parse_titles(self, response): for sel in response.css('html').extract(): data = {} data['title'] = response.css(r"h1[id='firstHeading'] i::text").extract() data['director'] = response.css(r"tr:contains('Directed by') a[href*='/wiki/']::text").extract() data['starring'] = response.css(r"tr:contains('Starring') a[href*='/wiki/']::text").extract() data['releasedate'] = response.css(r"tr:contains('Release date') li::text").extract() data['runtime'] = response.css(r"tr:contains('Running time') td::text").extract() yield data
The real work gets done in our parse_data function, where we create a dictionary called data and then fill each key with the information we want. Again, all these selectors were found using Chrome DevTools as demonstrated before and then tested with the Scrapy shell.
The final line returns the data dictionary back to Scrapy to store.
Complete code:
import scrapy, time class OscarsSpider(scrapy.Spider): name = "oscars" allowed_domains = ["en.wikipedia.org"] start_urls = ["https://en.wikipedia.org/wiki/Academy_Award_for_Best_Picture"] def parse(self, response): for href in response.css(r"tr[style='background:#FAEB86'] a[href*='film)']::attr(href)").extract(): url = response.urljoin(href) print(url) req = scrapy.Request(url, callback=self.parse_titles) time.sleep(5) yield req def parse_titles(self, response): for sel in response.css('html').extract(): data = {} data['title'] = response.css(r"h1[id='firstHeading'] i::text").extract() data['director'] = response.css(r"tr:contains('Directed by') a[href*='/wiki/']::text").extract() data['starring'] = response.css(r"tr:contains('Starring') a[href*='/wiki/']::text").extract() data['releasedate'] = response.css(r"tr:contains('Release date') li::text").extract() data['runtime'] = response.css(r"tr:contains('Running time') td::text").extract() yield data
Sometimes we will want to use proxies as websites will try to block our attempts at scraping.
To do this, we only need to change a few things. Using our example, in our def parse(), we need to change it to the following:
def parse(self, response): for href in (r"tr[style='background:#FAEB86'] a[href*='film)']::attr(href)").extract() : url = response.urljoin(href) print(url) req = scrapy.Request(url, callback=self.parse_titles) req.meta['proxy'] = "http://yourproxy.com:80" yield req
This will route the requests through your proxy server.
Deployment And Logging, Show How To Actually Manage A Spider In Production
Now it is time to run our spider. To make Scrapy start scraping and then output to a CSV file, enter the following into your command prompt:
scrapy crawl oscars -o oscars.csv
You will see a large output, and after a couple of minutes, it will complete and you will have a CSV file sitting in your project folder.
Compiling Results, Show How To Use The Results Compiled In The Previous Steps
When you open the CSV file, you will see all the information we wanted (sorted out by columns with headings). It’s really that simple.

Oscar winning movies list and information. (Large preview)
With data scraping, we can obtain almost any custom dataset that we want, as long as the information is publicly available. What you want to do with this data is up to you. This skill is extremely useful for doing market research, keeping information on a website updated, and many other things.
It’s fairly easy to set up your own web scraper to obtain custom datasets on your own, however, always remember that there might be other ways to obtain the data that you need. Businesses invest a lot into providing the data that you want, so it’s only fair that we respect their terms and conditions.
Additional Resources For Learning More About Scrapy And Web Scraping In General
The Official Scrapy Website
Scrapy’s GitHub Page
“The 10 Best Data Scraping Tools and Web Scraping Tools,” Scraper API
“5 Tips For Web Scraping Without Getting Blocked or Blacklisted,” Scraper API
Parsel, a Python library to use regular expressions to extract data from HTML.
(dm, yk, il)
0 notes
Text
Implementation of dark mode in reaction devices
One of the apps features most requested is the dark mode (or night mode, as others call it). In the apps which we use every day, we see dark mode. From smartphones to web applications, the dark mode has become important to businesses wishing to look after their users' eyes.
The dark mode is an add-on feature that often shows dark surfaces in the UI. Most big corporations (such as YouTube, Twitter, and Netflix) have brought their smartphone and web applications into dark mode.
Although we are not going to go into React and styled-components in detail, a simple knowledge of React,
CSS
, and styled-components would be useful.
A few days before this article was written,
StackOverflow
announced its release of dark mode, offering users the opportunity to switch between the two modes.
Dark mode eliminates eye pressure and aids when operating on a device or cell phone for a long period of time.
What Is Dark Mode?
The dark mode is the color scheme of any device showing light text and device elements on a dark backdrop, making it a little easier for the user to view cell phones, tablets, and computers. Dark mode decreases the light produced by the screen while preserving the minimum color-contrast ratios that are appropriate for reading.
Why Should You Care About Dark Mode?
Dark mode improves visual ergonomics by reducing eye strain, adapting the screen to current light conditions, and ensuring ease of use in dark environments or at night.Let's look at its benefits before we introduce dark mode in our app.
BATTERY SAVING
Dark mode in Web and mobile apps will extend a device's battery life. Google stated that dark mode on OLED screens has been a tremendous help to battery life.
For example, the dark mode in the YouTube app saves about 15 percent more screen energy than a flat white background at 50 percent brightness. The dark GUI saves a whopping 60 percent of screen energy at 100 percent screen brightness.
DARK MODE IS BEAUTIFUL
The dark mode is stunning, and can greatly enhance the screen's appeal.
Although most products go for the same bland white look, the dark mode offers something else that looks both mysterious and fresh.
It also offers great opportunities for a fresh presentation of graphic material, such as dashboards, videos, and images.
Now that you know why you should implement dark mode in your next web app, let's dive deep into style-components, which in this tutorial's defining resources.
The dark mode is the color scheme of any interface that displays light text and interface elements on a dark background, making viewing on mobile phones, tablets, and computers a little easier.
What Are Styled-Components?
We will be using the styled-components library very much in this post. There have always been a lot of ways to design a modern web application. A document-level there is the conventional styling approach which involves creating an index.css file and linking it to the HTML or styling within the HTML file.
A lot has changed in the way web apps are recently designed after CSS-in-JS was introduced.
CSS-in-JS refers to a pattern where JavaScript is used to compose the Html. To style components in a JavaScript file, it uses tagged template literals. The styled component is a CSS-in-JS library that allows you to use all the CSS features you need, including media queries, pseudo-selectors, and nesting.
Why Styled-Components?
For the following reasons styled-components were created:
No hell class name Instead of scratching your head to find an item class name, styled-components can create unique class names for your types. You will never have to think about misrepresentations, or using class names that have no meaning.
The use of designed component props allows one to expand the styling properties using the props parameter widely used in React — thereby dynamically influencing the component's feeling through the state of the application. Supports Sass syntax
Writing Sass syntax out of the box without having to set up any preprocessors or extra build tools is possible with styled-components. In your style definitions, you can use the & character to target the current component, use pseudo-selectors, and experiment with nesting.
• Theming modeled components have full thematic support through the export of a ThemeProvider wrapper. This framework provides a theme for all components of React within itself via the Context API. All styled-components will have access to the given theme in the rendering tree, even though they are deeply multi-level. As we continue this tutorial, we will investigate the thematic features of modeled components more deeply
SETTING UP
1. CREATE THE FILE STRUCTURE
Creating a folder and inserting within it three empty text files: one with.html, one with.css, and one with.js. Also, create a folder of images for the photos you wish to view on the website.
JQuery also makes use of our "dark mode in CSS" demo. In the example, we are going to add the script right from the Cloudflare CDN to the HTML file so that it is always up to date. If you like, however, you can download and add the jQuery library as a local.js file as well.
Here's how the file structure will look before coding begins:
- dark-mode-css/ - images/ - cake.jpg - index.html - script.js - style.css
2. MARK UP THE HTML
Add the dark-mode switch to the top of the page in the HTML. Then create a < h1 > title tag, and a semantic < article > tag for the page's content. Finally, just before the < /body > tag closes add the two < script > tags.
Please note that before the custom script you are adding the jQuery library so it can use its functionalities. The style.css file will go into the page's < head > section.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Demo | Dark Mode in CSS</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="switch">Dark mode: <span class="inner-switch">OFF</span> </div> <h1 class="title">The Best Recipes of All Time</h1> <article> <h1>Raspberry Cake</h1> <p><small>Created with Cupcake Ipsum</small></p> <p>...</p> <img src="images/cake.jpg"> <p>...</p> </article> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="script.js"></script> </body> </html>
3. CREATE THE CSS FOR THE LIGHT MODE
First, let's build the CSS for light mode, since this is the page's default state. The following CSS makes use of a column-based flexbox style that allows you to easily place elements on the page, specifically the.switch class that handles the dark mode toggle wrapper and the < img > elements.
body { font-family: sans-serif; font-size: 1.125rem; display: flex; flex-direction: column; max-width: 50rem; margin: 0 auto; padding: 0 0.9375rem; } small { font-style: italic; } article { display: flex; flex-direction: column; } img { max-width: 100%; display: block; align-self: center; } .switch { align-self: flex-end; margin: 0.9375rem; } .inner-switch { display: inline-block; cursor: pointer; border: 1px solid #555; border-radius: 1.25rem; width: 3.125rem; text-align: center; font-size: 1rem; padding: 0.1875rem; margin-left: 0.3125rem; }
The display: flex; rule applied to the tag allows the align-self to be used: flex-end; rule over the dark mode turn. The align-self CSS property aligns individual flex elements along the cross-axis (which is the left-to-right axis when a column is set to flex-direction).
In this way, the move is located automatically to the top right corner of the flex container — for all viewport sizes. .switch is a full-width layout row due to the flexbox, and its height does not fall at smaller screen sizes either.
Similarly, the display: flex; and flex-direction: column; rules added to the < article > tag allow align-self to be used: center; rule on all images inside the post. As a result, all the images can be conveniently focused without adding extra elements to the HTML, only for positioning purposes.
4. ADD THE SWITCH FUNCTIONALITY WITH JQUERY
The.js script file provides the toggle switch feature. Therefore, the dark mode is activated when the user clicks the toggle and the mark on the switch switches to "ON." And if, when the page is in dark mode, the user clicks the toggle, the light mode is added and the mark switches to "OFF."
$( ".inner-switch" ).on("click", function() { if( $( "body" ).hasClass( "dark" )) { $( "body" ).removeClass( "dark" ); $( ".inner-switch" ).text( "OFF" ); } else { $( "body" ).addClass( "dark" ); $( ".inner-switch" ).text( "ON" ); } });
The script above makes use of the following jQuery functions:
·
on(“click”, function() {…})
is an event handler that triggers the action inside the function when the user clicks the .inner-switch element,
·
hasClass()
checks if the .dark class is assigned to the .inner-switch element or not (this is based on the state of the toggle),
·
removeClass()
removes the .dark class from the HTML when the user switches to light mode,
·
addClass()
adds the .dark class to the HTML when the user switches to dark mode,
·
text()
sets the text of the label on the switch — it’s either “OFF” or “ON”.
· 5. ADD THE CSS FOR THE DARK MODE
The last thing you need to do is to define those styles for the.dark class that the jQuery script above added to the HTML when dark mode is turned on. In addition to the.dark class, apply the dark mode theme to both its direct and indirect children using the.dark * universal CSS selector.
.dark, .dark * { background-color: #222; color: #e6e6e6; border-color: #e6e6e6; }
The CSS belonging to the.dark class goes to the file ending with style.css. This is because CSS (= Cascading Style Sheets) is cascading in nature. The cascade may thus bypass the colors all over the page without bumping into specificity or other probelms.
You can also create a separate dark.css file for the dark mode styles if you are creating a more complex website. In this case, be careful that you always add the unique dark.css in the < head > section of the HTML after the generic style.css file, so that the cascade will work properly.
CREATING THEME-TOGGLING FUNCTIONALITY
1. Add HTML:
Using any item that should store the content for which you want the interface toggle. In our case, for simplicity we'll use < body >:
Example
<body>
Add CSS:
Design the item < body > and build a toggle class in.dark-mode:
Example
body { padding: 25px; background-color: white; color: black; font-size: 25px; } .dark-mode { background-color: black; color: white; }
3) Add JavaScript:
Get the < body > item and switch between the class of dark-mode:
Example
function myFunction() { var element = document.body; element.classList.toggle("dark-mode"); }
Conclusion
Dark mode is increasingly becoming a choice for the consumer, and it is much easier to integrate it into a web app by using the ThemeProvider theme wrapper in styled components. Go ahead and play with styled-components as you implement dark mode; you could add icons instead of a button.
As a reputed Software Solutions Developer we have expertise in providing dedicated remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to
get in touch with us!
#b2b website#b2b ecommerce b2b content marketing b2b seo b2b market research companies b2bservices Ecommerce#ecommerce
0 notes
Text
Advanced Tooling for Web Components
Over the course of the last four articles in this five-part series, we’ve taken a broad look at the technologies that make up the Web Components standards. First, we looked at how to create HTML templates that could be consumed at a later time. Second, we dove into creating our own custom element. After that, we encapsulated our element’s styles and selectors into the shadow DOM, so that our element is entirely self-contained.
We’ve explored how powerful these tools can be by creating our own custom modal dialog, an element that can be used in most modern application contexts regardless of the underlying framework or library. In this article, we will look at how to consume our element in the various frameworks and look at some advanced tooling to really ramp up your Web Component skills.
Article Series:
An Introduction to Web Components
Crafting Reusable HTML Templates
Creating a Custom Element from Scratch
Encapsulating Style and Structure with Shadow DOM
Advanced Tooling for Web Components (This post)
Framework agnostic
Our dialog component works great in almost any framework or even without one. (Granted, if JavaScript is disabled, the whole thing is for naught.) Angular and Vue treat Web Components as first-class citizens: the frameworks have been designed with web standards in mind. React is slightly more opinionated, but not impossible to integrate.
Angular
First, let’s take a look at how Angular handles custom elements. By default, Angular will throw a template error whenever it encounters an element it doesn’t recognize (i.e. the default browser elements or any of the components defined by Angular). This behavior can be changed by including the CUSTOM_ELEMENTS_SCHEMA.
...allows an NgModule to contain the following:
Non-Angular elements named with dash case (-).
Element properties named with dash case (-). Dash case is the naming convention for custom elements.
— Angular Documentation
Consuming this schema is as simple as adding it to a module:
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; @NgModule({ /** Omitted */ schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) export class MyModuleAllowsCustomElements {}
That’s it. After this, Angular will allow us to use our custom element wherever we want with the standard property and event bindings:
<one-dialog [open]="isDialogOpen" (dialog-closed)="dialogClosed($event)"> <span slot="heading">Heading text</span> <div> <p>Body copy</p> </div> </one-dialog>
Vue
Vue’s compatibility with Web Components is even better than Angular’s as it doesn’t require any special configuration. Once an element is registered, it can be used with Vue’s default templating syntax:
<one-dialog v-bind:open="isDialogOpen" v-on:dialog-closed="dialogClosed"> <span slot="heading">Heading text</span> <div> <p>Body copy</p> </div> </one-dialog>
One caveat with Angular and Vue, however, is their default form controls. If we wish to use something like reactive forms or [(ng-model)] in Angular or v-model in Vue on a custom element with a form control, we will need to set up that plumbing for which is beyond the scope of this article.
React
React is slightly more complicated than Angular. React’s virtual DOM effectively takes a JSX tree and renders it as a large object. So, instead of directly modifying attributes on HTML elements like Angular or Vue, React uses an object syntax to track changes that need to be made to the DOM and updates them in bulk. This works just fine in most cases. Our dialog’s open attribute is bound to its property and will respond perfectly well to changing props.
The catch comes when we start to look at the CustomEvent dispatched when our dialog closes. React implements a series of native event listeners for us with their synthetic event system. Unfortunately, that means that controls like onDialogClosed won’t actually attach event listeners to our component, so we have to find some other way.
The most obvious means of adding custom event listeners in React is by using DOM refs. In this model, we can reference our HTML node directly. The syntax is a bit verbose, but works great:
import React, { Component, createRef } from 'react'; export default class MyComponent extends Component { constructor(props) { super(props); // Create the ref this.dialog = createRef(); // Bind our method to the instance this.onDialogClosed = this.onDialogClosed.bind(this); this.state = { open: false }; } componentDidMount() { // Once the component mounds, add the event listener this.dialog.current.addEventListener('dialog-closed', this.onDialogClosed); } componentWillUnmount() { // When the component unmounts, remove the listener this.dialog.current.removeEventListener('dialog-closed', this.onDialogClosed); } onDialogClosed(event) { /** Omitted **/ } render() { return <div> <one-dialog open={this.state.open} ref={this.dialog}> <span slot="heading">Heading text</span> <div> <p>Body copy</p> </div> </one-dialog> </div> } }
Or, we can use stateless functional components and hooks:
import React, { useState, useEffect, useRef } from 'react'; export default function MyComponent(props) { const [ dialogOpen, setDialogOpen ] = useState(false); const oneDialog = useRef(null); const onDialogClosed = event => console.log(event); useEffect(() => { oneDialog.current.addEventListener('dialog-closed', onDialogClosed); return () => oneDialog.current.removeEventListener('dialog-closed', onDialogClosed) }); return <div> <button onClick={() => setDialogOpen(true)}>Open dialog</button> <one-dialog ref={oneDialog} open={dialogOpen}> <span slot="heading">Heading text</span> <div> <p>Body copy</p> </div> </one-dialog> </div> }
That’s not bad, but you can see how reusing this component could quickly become cumbersome. Luckily, we can export a default React component that wraps our custom element using the same tools.
import React, { Component, createRef } from 'react'; import PropTypes from 'prop-types'; export default class OneDialog extends Component { constructor(props) { super(props); // Create the ref this.dialog = createRef(); // Bind our method to the instance this.onDialogClosed = this.onDialogClosed.bind(this); } componentDidMount() { // Once the component mounds, add the event listener this.dialog.current.addEventListener('dialog-closed', this.onDialogClosed); } componentWillUnmount() { // When the component unmounts, remove the listener this.dialog.current.removeEventListener('dialog-closed', this.onDialogClosed); } onDialogClosed(event) { // Check to make sure the prop is present before calling it if (this.props.onDialogClosed) { this.props.onDialogClosed(event); } } render() { const { children, onDialogClosed, ...props } = this.props; return <one-dialog {...props} ref={this.dialog}> {children} </one-dialog> } } OneDialog.propTypes = { children: children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node ]).isRequired, onDialogClosed: PropTypes.func };
...or again as a stateless, functional component:
import React, { useRef, useEffect } from 'react'; import PropTypes from 'prop-types'; export default function OneDialog(props) { const { children, onDialogClosed, ...restProps } = props; const oneDialog = useRef(null); useEffect(() => { onDialogClosed ? oneDialog.current.addEventListener('dialog-closed', onDialogClosed) : null; return () => { onDialogClosed ? oneDialog.current.removeEventListener('dialog-closed', onDialogClosed) : null; }; }); return <one-dialog ref={oneDialog} {...restProps}>{children}</one-dialog> }
Now we can use our dialog natively in React, but still keep the same API across all our applications (and still drop classes, if that’s your thing).
import React, { useState } from 'react'; import OneDialog from './OneDialog'; export default function MyComponent(props) { const [open, setOpen] = useState(false); return <div> <button onClick={() => setOpen(true)}>Open dialog</button> <OneDialog open={open} onDialogClosed={() => setOpen(false)}> <span slot="heading">Heading text</span> <div> <p>Body copy</p> </div> </OneDialog> </div> }
Advanced tooling
There are a number of great tools for authoring your own custom elements. Searching through npm reveals a multitude of tools for creating highly-reactive custom elements (including my own pet project), but the most popular today by far is lit-html from the Polymer team and, more specifically for Web Components, LitElement.
LitElement is a custom elements base class that provides a series of APIs for doing all of the things we’ve walked through so far. It can be run in a browser without a build step, but if you enjoy using future-facing tools like decorators, there are utilities for that as well.
Before diving into how to use lit or LitElement, take a minute to familiarize yourself with tagged template literals, which are a special kind of function called on template literal strings in JavaScript. These functions take in an array of strings and a collection of interpolated values and can return anything you might want.
function tag(strings, ...values) { console.log({ strings, values }); return true; } const who = 'world'; tag`hello ${who}`; /** would log out { strings: ['hello ', ''], values: ['world'] } and return true **/
What LitElement gives us is live, dynamic updating of anything passed to that values array, so as a property updates, the element’s render function would be called and the resulting DOM would be re-rendered
import { LitElement, html } from 'lit-element'; class SomeComponent { static get properties() { return { now: { type: String } }; } connectedCallback() { // Be sure to call the super super.connectedCallback(); this.interval = window.setInterval(() => { this.now = Date.now(); }); } disconnectedCallback() { super.disconnectedCallback(); window.clearInterval(this.interval); } render() { return html`<h1>It is ${this.now}</h1>`; } } customElements.define('some-component', SomeComponent);
See the Pen LitElement now example by Caleb Williams (@calebdwilliams) on CodePen.
What you will notice is that we have to define any property we want LitElement to watch using the static properties getter. Using that API tells the base class to call render whenever a change is made to the component’s properties. render, in turn, will update only the nodes that need to change.
So, for our dialog example, it would look like this using LitElement:
See the Pen Dialog example using LitElement by Caleb Williams (@calebdwilliams) on CodePen.
There are several variants of lit-html available, including Haunted, a React hooks-style library for Web Components that can also make use of virtual components using lit-html as a base.
At the end of the day, most of the modern Web Components tools are various flavors of what LitElement is: a base class that abstracts common logic away from our components. Among the other flavors are Stencil, SkateJS, Angular Elements and Polymer.
What’s next
Web Components standards are continuing to evolve and new features are being discussed and added to browsers on an ongoing basis. Soon, Web Component authors will have APIs for interacting with web forms at a high level (including other element internals that are beyond the scope of these introductory articles), like native HTML and CSS module imports, native template instantiation and updating controls, and many more which can be tracked on the W3C/web components issues board on GitHub.
These standards are ready to adopt into our projects today with the appropriate polyfills for legacy browsers and Edge. And while they may not replace your framework of choice, they can be used alongside them to augment you and your organization’s workflows.
The post Advanced Tooling for Web Components appeared first on CSS-Tricks.
😉SiliconWebX | 🌐CSS-Tricks
0 notes
Text
To Acquire Or Not To Purchase Vehicle Purchasing Guidebook
Buying a brand name new auto is one particular of the greatest thoughts in the globe. However, that experience can speedily turn hideous if your vehicle offers you a headache a few limited months soon after you obtain it. Use the advice provided in this post to guarantee that you make a wise variety when buying your subsequent auto. Often provide a mechanic alongside when buying for a new car. Automobile dealers are infamous for selling lemons and you do not want to be their next sufferer. If you can not get a mechanic to look at vehicles with you, at the very least be confident that you have him appear at your closing selection ahead of you purchase it. Do not pay out sticker price tag for a car. What the sellers record on the sticker is not what they really think they will get. If negotiation is not something that you personally excel at, carry along an individual that does. You can figure out the most you might be willing to spend by researching the worth of the cars you are intrigued in forward of time. The check generate is a single of the most crucial steps in the approach of auto searching. This is accurate even if you have pushed yet another vehicle of the identical model. It truly is critical to know how this exact car handles. There may possibly be a refined variation or a mechanical situation that may possibly elude you if you hadn't driven it. Lookup for your new auto on-line prior to you at any time check out a dealership. Browsing on-line permits you to seem at inventory from numerous dealerships, and it makes you privy to info about on the web only pricing. This is a wonderful way to comparison store and actually make sure you are getting the greatest offer. Be cautious of any supplier who is not inclined to give you an extended examination push. Inquiring for a full afternoon to take a look at out the car is a properly sensible request. If the dealer refuses and will not accommodate the request, you need to get your company somewhere else. A vehicle is a large buy and a big determination, a vendor need to comprehend that and enable you get entirely cozy with the automobile just before getting. Only use reviews on the web as a general guide. A great deal of folks when they have problems with a vehicle will submit unfavorable evaluations on the world wide web. So seem at all the evaluations for common issues as opposed to a general ranking. If there is 2020 ford mustang sedan with a major part, then possibly uncover a distinct motor vehicle. Keep away from being distracted when you are buying at a automobile whole lot. With so a lot of automobiles offered, it is straightforward for all your analysis and planning to go out the window. Remember, you should have a very clear notion of the automobile you want just before you set foot on the whole lot, and do not permit the salesperson steer you from your purpose. Consider 2020 honda accord sedan when getting a new automobile and do your research. Do not be scared to get up and stroll absent from a deal. Don't drop in love with a specific automobile. If the figures the dealer is supplying you are not what you want, just stroll absent. Find out all you can about rebates. You can both get a cash rebate, minimal mortgage interest fee or the seller them selves gets the rebate in income. It is the maker who offers these rebates, not the dealership. This will only be available on vehicles offered on the good deal, of training course. Stand organization on your down payment. Autos can be sold with no down payment even so, some cash down will help the final cost. Be wary of sellers who inquire you to increase your down payment. This additional funds will typically only go into the pocket of the salesperson and dealership, and does not support your base line. Watch out for https://gracecervantes7.livejournal.com/431.html marketing charges. These are often tacked on to new automobile buys, and you must not have to pay out them. Vehicle dealerships have to market as part of undertaking organization, and several consumers who obstacle this charge will acquire. If your salesman will not eliminate this charge, inquire to speak with a supervisor. It is unlawful for a seller ship to roll back the odometer on any car they sell. Even if they put a new motor in the car, it is nevertheless illegal. If you suspect that a dealer is not stating the correct mileage on a vehicle, depart and store somewhere else. If you are planning on utilizing your current automobile as a trade in, never enable the supplier know correct away. Your very first objective is to negotiate down the price of the vehicle you want to buy. Info like trade-in worth is worthwhile to the salesman, so keep it to your self until finally the correct instant! You ought to now have a much better concept of what it will take to acquire a car that you can be happy with for several years to arrive. Make confident to employ the advice offered so that you do not end up producing a purchase you regret. With a tiny tolerance and data, you can stop up with a wonderful auto!
0 notes