投稿時間:2021-10-18 00:24:35 RSSフィード2021-10-18 00:00 分まとめ(25件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… 新型「MacBook Pro」に搭載されるチップの名称は「M1 Pro」や「M1 Max」になる可能性も https://taisy0.com/2021/10/17/147455.html macbookpr 2021-10-17 14:17:32
js JavaScriptタグが付けられた新着投稿 - Qiita javascript演習 2日目、3日目/30日 https://qiita.com/Qubieeee/items/68f3455e6d474c1d62cc javascript演習日目、日目日覚えたことたち秒ごとに度回転させるconstnownewDateconstsecondsnowgetSecondsconstsecondsDegreesecondssecondHandstyletransformrotatesecondsDegreedegードキュメントのルート要素にcssの変数を設定するrootbaseffcspacingpxblurpximgpaddingvarspacingbackgroundvarbasefilterblurvarblurjavascriptでhtmlタグのアトリビュートを操作するltaudiodatakeygtとかのタグをdatakeyで絞り込むconstaudiodocumentquerySelectoraudiodatakeyekeyCodeltinputdatasizingpxgtとかのタグのdatasizingを取得するconstsuffixthisdatasetsizingドキュメントのルート要素にcssスタイルをjavascritでつけるこれでルートにつけたcssの変数をリアクティブに変更できる。 2021-10-17 23:58:40
js JavaScriptタグが付けられた新着投稿 - Qiita Internet Explorer から Edge にシームレスに案内するスクリプト https://qiita.com/nanakochi123456/items/e119a582dac242602d8b InternetExplorerからEdgeにシームレスに案内するスクリプトスクリプトvaruanavigatoruserAgenttoLowerCaseifuamatchmsietridentvarurllocationprotocollocationhostnamelocationpathnamevarmsgltspanstylefontsizepxgt当サイトは年の歴史を歩んできたInternetExploerのサポートを終了しました。 2021-10-17 23:10:49
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 二分法の検算結果の絶対値が、前の値より大きくなってしまう。 https://teratail.com/questions/364904?rss=all 二分法の検算結果の絶対値が、前の値より大きくなってしまう。 2021-10-17 23:48:59
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) dfにおける上の行との差の正負により、グラフの線分の色を変えたい https://teratail.com/questions/364903?rss=all dfにおける上の行との差の正負により、グラフの線分の色を変えたい前提・実現したいことある地点での時系列データより波高を縦軸、波周期を横軸とした散布図を作成し、点を直線で結んだグラフを作成しています。 2021-10-17 23:41:03
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) ダイアログ表示後のインタースティシャル広告実装方法 https://teratail.com/questions/364902?rss=all ダイアログ表示後のインタースティシャル広告実装方法初心者です。 2021-10-17 23:31:26
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Djangoでcssが反映されない https://teratail.com/questions/364901?rss=all Djangoでcssが反映されないDjangoのCSSを反映させたいここに質問の内容を詳しく書いてください。 2021-10-17 23:25:10
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) AtCoder エラーが1つ取れない https://teratail.com/questions/364900?rss=all AtCoderエラーがつ取れない問題問題はこちらから方針左及び右からそれぞれ火がスタートして、各接着点に到達するまで何秒かかったかを累積和でleftとrightに取り、各項の差がマイナスからプラスに転じる地点nbspnbspちょうどになる地点をpointとし、pointから衝突地点までの距離をxとして距離を求めました。 2021-10-17 23:17:46
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) discord.pyを使用して、DiscordBOTのステータスを定期的に変更したい https://teratail.com/questions/364899?rss=all discordpyを使用して、DiscordBOTのステータスを定期的に変更したい前提・実現したいことdiscordpyの、discordexttasksを使用して定期的にBOTのステータスを変えたいです。 2021-10-17 23:04:52
Linux CentOSタグが付けられた新着投稿 - Qiita 【Mac】VirtualBoxを使ってCentOS7のWEBサーバー構築 https://qiita.com/shi_design_/items/0f1219c3f29476b4a157 Linuxのコマンドやvimの操作に不慣れな部分があったのですが、その練習にもなったので良かったですVirtualBoxをインストールこちらにアクセスして、VirtualBoxをダウンロードします。 2021-10-17 23:18:54
Ruby Railsタグが付けられた新着投稿 - Qiita 【rails × vue】 ライブラリでフラッシュメッセージを表示する https://qiita.com/Yuya-hs/items/49631133ab9aacd3aaa3 timethisflashMessageshowtypeメッセージの種類titleタイトルメッセージtextメインメッセージtimeメッセージを表示する時間thisflashMessageshowでメッセージの挿入が行えます。 2021-10-17 23:35:11
Ruby Railsタグが付けられた新着投稿 - Qiita booleanをランダムで返す https://qiita.com/tkht2401/items/63406354e17566e3ae11 hogetruefalsesample 2021-10-17 23:31:25
技術ブログ Developers.IO エアコンをSwitchBotにカスタマイズモードで登録してAlexaで操作してみた https://dev.classmethod.jp/articles/switchbot-registering-the-air-conditioner-in-customize-mode-and-try-to-control-it-with-alexa/ switchbot 2021-10-17 14:54:55
海外TECH DEV Community Learn SQL: Microsoft SQL Server - Episode 1: Introduction https://dev.to/ifierygod/learn-sql-microsoft-sql-server-episode-1-introduction-33oa Learn SQL Microsoft SQL Server Episode Introduction Over the last decade the amount of data that systems and devices generate has increased significantly Because of this increase new technologies roles and approaches to working with data are affecting data professionals MicrosoftSQL is one of the most sought after skills for one simple reason Data is everywhere Organisations are collecting tons of data about their customers and employees interactions with various channels whether it is online offline in store sales purchase data employee data employee interaction data financial data and tons of third party data All this information ends up in a database or databases where companies will analyse the data to make sense of it and ultimately make critical business decisions Organisations who are not using data are being left behind that s the reason why many organisations understand the value of data and the advantages of data analysis To provide analysis you need SQL skills Whether you are trying to become a financial analyst marketing analyst digital analyst or data scientist Having solid SQL skills are a must and empowers you We will be using Microsoft SQL Server Express Edition this version is free whatever you will learn in this version applies to other versions as well You can download it by using the link below SQL Server Express EditionAlternatively you can browse to find it by searching for sql server express in your favourite browser Once you have downloaded and started installing it will take a while before the installation is complete After the installation has completed successfully you will see a bunch of information that shows you exactly in which directories the files are in case you need them Below we will see a button that reads Install SSMS this is the SQL Server Management Studio It is where we will be writing our sql queries and all the manipulation What we have been doing up until now is installing the database which is in the backend and SSMS is the frontend we will be using to manipulate our data and interact with the database After the SSMS is installed we need to restart the computer Make sure to save and close all the important programs then restart Once we restarted and are back on our desktop we can find the SSMS by searching for it Open it up and we will be prompted to enter the server name and authentication just leave it as is since it is your default connectivity if we are connecting to the server that we just installed If you have credentials to another server then you will enter it here SQL SERVER STRUCTUREBefore proceeding to write sql server queries let s first look at how sql server is structured In SQL up on top we have a server think of it as a physical machine we are connecting to Under each server we can have multiple databases Databases are entities containing all the data structured in various tables Under each database we have schema s think of schema s as the ownership structure Essentially meaning within each database we can have different owners For instance sales team that owns their own schema and objects underneath and another schema that belongs to customer service Under each schema we have what are called objects Objects are entities such as tables stored procedures views etc Our main focus will be on tables Let s see how this structure looks inside of SSMS As you can see we are already connected to a server as shown right above We are able to connect to many servers in this interface and all of them will appear underneath each other We can connect to another server by clicking on file at the top left and choosing the Connect Object Explorer option This will open a window which requires us fill in the details of the second server to access that particular database We can click cancel since we are not connecting to another database Expand the server underneath the server we will see the databases if we expand it we will most likely not see any databases because we haven t created any databases yet We will be using a demo database in order to get familiar with SSMS This demo database is called AdventureWorks You can download it by following the link below AdventureWorks Remember choose the OLTP AdventureWorks bak fileOnce downloaded we store it somewhere easy to find since we need to locate it from SSMS to restore AdventureWorks on our newly created database Store the bak file in your C Drive Program Files Windows SQL Server for convienience Back on SSMS right click the databases folder and choose Restore Database a window will open We need to choose the device option and then click on the ellipsis on the right end of the window they look like three dots A window called select backup devices will open click on the add button on the middle right of the window We need to find the bak file we downloaded earlier Once we find it we need to add it and click OK Then click OK again to add it to the databases folder When we click on the AdventureWorks database it will show us another set of folders this is how a database organises objects underneath it We will be looking at Tables this is where all the data gets stored here we can see all the list of tables Table are prefixed with the schemaName The schemaName defines who owns the schema If things are not completely clear do not fret Things will become more digestible as we continue on this journey together On the SSMS menu options above When we click on New Query it will open a window which is where we will write all our SQL queries On the left of the menu you will see a dropdown it will indicate which database we are currently connecting to When you first click on New Query it might connect to the master database Remember if you want to run a query correctly you need to be in the correct database We won t be using the master database because it is used by SQL internally What is Normalisation Most of the data that is organised in SQL Server is organised in a normalised way Normalization is the process of breaking up data into smaller chunks that are less redundant It allows us to insert delete and update tuples rows without introducing database inconsistencies It stores data in a way that prevents us from changing a data point in multiple places This means when we change a data point the change is reflected everywhere This is also meant to remove inconsistent dependency which means to store data in a way that makes logical sense Let s say you have a table about employee s in that table you would only store information about the employee s and not every single detail about a department that the employee belongs to The department information will reside in a department table We can use a table visually understand the concept of normalisation In the example below we have a customer table that contains information about all the customers Each row represents a different customer Customer IDFirstNameLastnameCompanyStateMain StoreJamesButtMicrosoftDallasMallJosephineDimsonDellWashingtonStrip mallRibCollarGoogleDallasMallBarryWhiteMicrosoftCaliforniaSquareIanSimsGoogleNew YorkSquareMichelleNielAsusTexasMallGregLawsonDellWashingtonStrip mallThis is an example of denormalised data Notice how we have inserted the same company name for different customers If for instance Microsoft decided to change its name to Tfosorcim Then we would need to change the company name in multiple rows and this could result in errors or inconsistencies The same applies to the State and Main Store columns AdvantageWe can find all the data we need for a single customer or multiple customers from this approach since it s all stored in one table DisadvantageA disadvantage of this way of storing data is how it cost us storage to have the same data point inserted at multiple times This is where creating a normalised database can benefit us Instead of creating one giant table we create multiple tables Let s normalise this information Customer TableCustomer IDFirstNameLastnameCompanyStateMain StoreJamesButtDAJosephineDimsonWARibCollarDABarryWhiteCAIanSimsNYMichelleNielTXGregLawsonWA Store TableStore IDStoreMallSquareStrip mall State TableState IDStateDADallasCACaliforniaWAWashingtonNYNew YorkTXTexas Company TableCompany IDCompanyMicrosoftDellAsusGoogleThis is an example of a normalised database structure As you can see we still have one customer table with all the columns But we have added additional tables called Store State and Company These additional tables have ID s associated with their different data points Instead of added the company name in each row for a customer we add the ID of a related table that points to that data So now for example ID number means Microsoft If for instance Microsoft were to change its name we would no longer need to change the name in multiple places all we need to do is change it in one location and all tables that use the data point will reflect that change AdvantageWe get the advantage of less storage since we are not repeating ourselves by adding in the complete data point but rather the ID DisadvantageThe downside of this approach is we need to look into multiple tables to find the data that we need That concludes the introduction to Windows SQL Server SSMS and SQL Data Structures Now that we have setup our database next up will be quering a database We still have a long way to go so stay awesome and stay zen 2021-10-17 14:37:47
海外TECH DEV Community How to Build a Music Streaming App with React using Auth0 and Cloudinary https://dev.to/hackmamba/how-to-build-a-music-streaming-app-with-react-using-auth0-and-cloudinary-6k9 How to Build a Music Streaming App with React using Auth and CloudinarySince its debut music streaming has developed dramatically and it is currently one of the most acceptable methods to listen to music Many streaming sites let you hear for free which has reduced the need for piracy while ensuring that artists are compensated fairly It s also very accessible with numerous possibilities We ll learn how to use Auth and Cloudinary to develop a music streaming app in this tutorial SandboxThis project was completed in a Codesandbox To get started quickly fork the Codesandbox or run the project GitHub Repository Olanetsoft music app with auth and cloudinary Created with CodeSandbox music app with auth and cloudinaryCreated with CodeSandbox View on GitHub What is Auth Auth is an extensible authentication and authorisation system that is simple to set up It also provides a complete identity and access management system that works right out of the box with the ability to customise expand and develop new features as needed What is Cloudinary Cloudinary provides a secure and comprehensive API for uploading media files fast and efficiently from the server side the browser or a mobile application We can upload media assets using Cloudinary s REST API or client libraries SDKs These SDKs wrap the upload API and make it easier to integrate with websites and mobile apps Creating a new React project and Installing dependenciesTo create a new project we use the npx create react app command to scaffold a new project in a directory of our choice To install the dependencies we will be using the command below cd lt project name gt npm install auth auth react supabase supabase js bootstrap moment react audio player react bootstrap react helmetOnce the app is created and the dependencies are installed we will see a message with instructions for navigating to our site and running it locally We do this with the command npm startReact js will start a hot reloading development environment accessible by default at http localhost Setting Up Auth AccountKindly visit Auth to sign up if you haven t or login to dashboard click the Applications dropdown then application and finally click the Create Application button as shown below We can now create our application as shown below As shown below we have successfully created our application but we need to set URLs to point back to our application Scroll down to the Application URIs section and set the followingAllowed Callback URLs Allowed Logout URLs Allowed Web Origins Replace with our application URL or http localhost that we set up earlier We will be making use of Domain and Client ID in our application later in this tutorial Setting up our Application UI and Auth integration Let s import and set up our application to use the bootstrap dependencies we installed Navigate to public index html update the file by linking the bootstrap CSS and js with the snippet below Adding CSS reference lt DOCTYPE html gt lt html lang en gt lt head gt lt link rel stylesheet href dist css bootstrap min css integrity sha FwmXPdgyTmZZMECAngseQBDfGTowiiMjiWaeVhAnFJkqJByhZMIAhiU crossorigin anonymous gt lt title gt Music Streaming App lt title gt lt head gt lt body gt lt body gt lt html gt Adding JS reference lt DOCTYPE html gt lt html lang en gt lt head gt lt head gt lt body gt lt noscript gt You need to enable JavaScript to run this app lt noscript gt lt div id root gt lt div gt lt script src crossorigin gt lt script gt lt script src crossorigin gt lt script gt lt script src next dist react bootstrap min js crossorigin gt lt script gt lt body gt lt html gt We require the user interface to stream music on the home page We will create this by updating the app js file to a component Since it is the React tradition to work with a component structure we will create a folder called components in the src folder and create header js music js and musicList js components In the components music js file let us update it with the snippet below import ReactAudioPlayer from react audio player import moment from moment export default function Music musicList index return lt div className col md gt lt div className card p mb key index gt lt div className d flex justify content between gt lt div className d flex flex row align items center gt lt div className icon gt lt i className bx bxl mailchimp gt lt i gt lt div gt lt div className ms c details gt lt h className mb gt musicList name lt h gt lt span gt moment musicList created at format MMMM Do YYYY lt span gt lt div gt lt div gt lt div className badge gt lt span role img aria label gt Hot lt span gt lt div gt lt div gt lt div className mt gt lt h className heading gt musicList title lt h gt lt div className mt gt lt ReactAudioPlayer src musicList url controls gt lt div gt lt div gt lt div gt lt div gt In the snippet above we created a component for a single music card with musicList and index props We also imported ReactAudioPlayer and moment for the audio player and upload date formatting respectively Inside the musicList js component we will update it with the snippet below by importing the music component and iterating through the sample musicList array import Music from music export default function App const musicList name olanetsoft title Bang Bang url created at T Z return lt div className row gt musicList map m key gt lt Music musicList m index key gt lt div gt Let us update the header js component we created earlier with the snippet below import Button from react bootstrap export default function Header return lt div className d flex flex column flex md row align items center p px md mb bg white border bottom shadow sm gt lt h className my mr md auto font weight normal gt Music Streaming App with Auth and Cloudinary lt h gt lt nav className my my md mr md gt lt a className p text success href gt Home lt a gt lt a className p text danger href gt Trending lt a gt lt a className p text info href gt Top Songs lt a gt lt nav gt lt Button id btnUpload className btn margin variant primary gt Upload Song lt Button gt lt div gt We can now update our src app js file as shown below import MusicList from components musicList import styles css export default function App return lt div className container mt mb gt lt Header gt lt MusicList gt lt div gt The current user interface doesn t look aesthetically pleasing we ll add some styling with CSS We will update src styles css file with the following content in this GitHub Gist Our application should now look like this on http localhost We re currently working with sample data which is not ideal We should be able to upload and stream songs that others have uploaded We ll use Auth to track who s uploading new songs and then we ll use Cloudinary to do the actual uploading before saving it to the database Setting up Auth in our ApplicationLet s create env file in root of our project and populate it with Domain and Client ID from our Auth dashboard with the snippet below AUTH DOMAIN dev hbpok us auth com AUTH CLIENT ID tdYpNQQqjymidOCwZdGGWlYCNFRInside src index js let us import AuthProvider and setup our application with the snippet below import StrictMode from react import ReactDOM from react dom import App from App import AuthProvider from auth auth react const domain process env AUTH DOMAIN const clientId process env AUTH CLIENT ID const rootElement document getElementById root ReactDOM render lt StrictMode gt lt AuthProvider domain domain clientId clientId redirectUri window location origin gt lt App gt lt AuthProvider gt lt StrictMode gt rootElement We can now create login button js logout button js and loading js component inside components folder respectively using the snippet below Inside components login button js import useAuth from auth auth react import Button from react bootstrap export default function Login const loginWithRedirect useAuth return lt Button id btnLogin className btn margin onClick gt loginWithRedirect variant primary gt Upload Music lt Button gt components logout button js import useAuth from auth auth react import Button from react bootstrap export default function Logout const logout useAuth return lt Button id btnLogin className btn margin onClick gt logout variant danger gt Logout lt Button gt Then inside components loading js import src styles css export default function Loading return lt div className spinner gt lt div gt We may proceed to import the login and logout component inside header js file created earlier as shown below import useState useEffect from react import Button from react bootstrap import useAuth from auth auth react import Login from components login button import Logout from components logout button export default function Header const isAuthenticated useAuth return lt div className d flex flex column flex md row align items center p px md mb bg white border bottom shadow sm gt isAuthenticated lt gt lt div gt lt Button id btnUpload className btn margin variant primary gt Upload Song lt Button gt amp nbsp amp nbsp lt Logout gt lt div gt lt gt lt Login gt lt div gt Updating src app js import Loading from components loading export default function App const isLoading useAuth if isLoading return lt Loading gt return Let us test our application and we should have something similar to what we have below after clicking the Upload Song button In the screenshot above we ve successfully logged in and you ll notice that the UI in the header has changed to include a logout button Configuring Cloudinary and DB to Upload SongsWe will be using Cloudinary s upload widget because of its ability lets us upload media assets from multiple sources including Dropbox Facebook Instagram Create a free cloudinary account to obtain your cloud name and upload preset Upload presets allow us to centrally define a set of asset upload choices rather than providing them in each upload call A Cloudinary cloud name is a unique identifier associated with our Cloudinary account First from a content delivery network CDN we will include the Cloudinary widget s JavaScript file in our index js located in src app js We include this file using the react helmet s lt Helmet gt component which lets us add data to the Head portion of our HTML document in React import styles css import Helmet from react helmet export default function App return lt div className container mt mb gt lt Helmet gt lt meta charSet utf gt lt script src type text javascript gt lt script gt lt div gt The widget requires our Cloudinary cloud name and uploadPreset The createWidget function creates a new upload widget and on the successful upload of either a video or audio we assign the public id of the asset to the relevant state variable To get our cloudname and uploadPreset we follow the steps below The cloud name is obtained from our Cloudinary dashboard as shown below An upload preset can be found in the “Upload tab of our Cloudinary settings page which we access by clicking on the gear icon in the top right corner of the dashboard page We then click on the Upload tab on the settings page We scroll down to the bottom of the page to the upload presets section where we see our upload preset or the option to create one if we don t have any Let us update our components header js with the snippet below Let us open our app in the browser and click the Upload Song button we should see something like this We can further customise the widget with more information in this documentation We have successfully configured and setup cloudinary in our application but we will also integrate a supabase database to save all of the songs that users have uploaded let us create client js to integrate supabase with the sippet below import createClient from supabase supabase js const URL const ANNON PUBLIC SECRET eyJhbGciOiJIUzINiIsInRcCIIkpXVCJ eyJybxlIjoiYWvbiIsImlhdCIMTYzMzMNzUOSwiZXhwIjoxOTQOTQzNgYfQ uBBXtyxbwKixUgqltiYUsqOgSPyBmLSckybqPCPI export const supabase createClient URL ANNON PUBLIC SECRET To get the url and annon public key create a supabase account start a new project go to settings then Api tab We ll create a new table named songs with columns for url name and title by going to the table editor tab on the sidebar Let s ensure the column type is text for all the columns created After successfully creating our table let s update the components header js file with the snippet below In the preceding code line We created state variables that are updated when the upload is completed We created a function called createSong that connects to the songs table in Supabase and then we input our data We then verify the variables to ensure they aren t undefined before using the createPost method to save them in the database Let s update the musicList component to retrieve all uploaded songs with the snippet shown below import useState useEffect from react import supabase from client import Music from music export default function App const musicList setMusicList useState useEffect gt fetchSongs async function fetchSongs const data await supabase from songs select setMusicList data return lt div className row gt musicList map m key gt lt Music musicList m index key gt lt div gt Voila We are all set we can now successfully upload songs stream songs etc ConclusionThis article explains how to use Auth and Cloudinary to build a music streaming app utilising Cloudinary s widget capability ResourcesMedia upload on CloudinaryReact HelmetAuthContent created for the Hackmamba Jamstack Content Hackathon using Auth and Cloudinary 2021-10-17 14:30:54
海外TECH DEV Community How to Implement a Dark Mode with CSS and 3 Simple Lines of Javascript https://dev.to/daveyhert/how-to-implement-a-dark-mode-with-css-and-3-simple-lines-of-javascript-576 How to Implement a Dark Mode with CSS and Simple Lines of JavascriptThere s no denying that a must have feature of most modern websites and web apps is the ability to toggle the site s theme from a light mode to that of a dark one this feature has gradually become a trendy addition to the modern web and knowing how to go about implementing it is undeniably going to come in handy when working on future projects or implementing it on pre existing projects As with everything in programming there are a thousand and more ways to go about doing anything and implementing a dark mode on a website is no different there are several ways but in this article we ll be looking at one of such ways PrerequisiteBasic knowledge of HTML and CSS Very basic knowledge of JavaScript or not as I d explain everything You ve read the article on how to make a CSS Toggle Switch Optional Getting into CSS Custom Properties CSS Variables As in every programming language variables are simply names given to memory locations where values can easily be stored which then makes the variable reusable in our program rather than repeating hardcoding the actual values in multiple places in our code This as you probably know makes it easy to implement a global change by changing the value of the variable where it is defined declared which in turn reflects in every instance of that variable the value of the variable changes where ever the variable has been used Fortunately CSS specification allows for the use of such variables known as custom CSS properties These custom properties are defined as a name value pair combination that can then be associated with an element Defining the name of the variable is initiated using double hyphen two dashes followed by the name of the custom property and finally assigning a value to it e g example primary color To use this custom primary color property in a rule you d have to call the var function with the name of the custom property passed to it e g example background color var primary color This as you d have guessed is the same as setting background color because the variable primary color is a placeholder for the actual value it holds ScopeDepending on where these variables are defined they can either have a global scope which means they can be accessed and used anywhere in our stylesheet or a local scope that limits its usage to a specific rule To give a variable a global scope it would have to be stored in the root pseudo class selector in our stylesheet This root selector targets the root element in our HTML markup which is the lt html gt element in our document You can simply think of the root selector as a representation of the lt html gt element but with higher specificity priority root primary color By declaring this variable in the root selector pseudo class it is given a global scope and can be used anywhere in our stylesheet E g h color var primary color div background color var primary color To give a variable a local scope it would have to be defined in a ruleset and will only be accessible within that ruleset local scope E g element primary color fff color var primary color border px solid var primary color Overriding Global Variables with Local VariablesThe most interesting feature of these variables is the fact that when a variable that is already defined in the root global scope is redeclared in a ruleset local scope with a new value the new value overrides that of the global scope but only within that ruleset E g root primary color h primary color e color var primary color h color var primary color Output Implementing a Dark Mode FeatureWith our current knowledge of CSS variables implementing a dark mode feature is pretty straightforward For this tutorial we ll be using a CSS toggle switch previously made in a different article you can quickly jump to that article if you are curious about how this toggle switch was made HTML MarkupFor the HTML markup we ll simply place this toggle switch and a div containing a bunch of content lt body gt lt Toggle Switch gt lt div class switch gt lt input type checkbox id switch gt lt label for switch gt lt i class fas fa sun gt lt i gt lt i class fas fa moon gt lt i gt lt span class ball gt lt span gt lt label gt lt div gt lt Content of Our Webpage gt lt div class content gt lt h gt Heading lt h gt lt p gt Lorem ipsum dolor sit amet consectetur adipisicing elit Expedita non lt p gt lt div gt lt body gt OutputTo keep things simple that s all the HTML we ll be needing for this implementation The idea is that the content section represents the entire content of our webpage and the toggle is what we click on to trigger a change in our webpage CSS MarkupThis is where our CSS custom properties variables play a key role the concept is that rather than using hardcoded values for styling our site s color scheme various colors on our site we store the color scheme of the site s initial mode light mode as variables in the root global scope of our stylesheet and then use these variables in places where we d normally use normal hardcoded values So let s do just that root bg color fff primary text color secondary text color We ve created three custom variables in our global root element now we ll proceed to style our webpage using these variables Let s start by centering everything on the webpage using flex giving our webpage a background color and giving the content two distinct colors using these variables body display flex height vh flex direction column justify content center align items center background var bg color content color var primary text color content p color var secondary text color OutputNow we are going to create a dark theme class ruleset and redefine our global variables with new values that are tailored for a dark mode outlook dark mode bg color ec primary text color fff secondary text color ddd The new values in the dark mode class is what will be used to override the values of the global variables when ever the toggle is switched on this is done by using JavaScript to add this newly created dark mode class to our lt body gt element meaning any element within the scope of the body of our webpage will have the dark mode applied to it The Magic Lines of JavaScript const switchTheme document querySelector switch switchTheme addEventListener click function document body classList toggle dark mode For those new to or unfamiliar with JavaScript here is the breakdown of what the code above is doing const switchTheme document querySelector switch We are simply asking JavaScript to query the DOM look for an element in the webpage that has an ID of switch and then store this element in a constant variable switchTheme addEventListener click function Now accessing that toggle element using the variable name we ask JavaScript to listen to a click event and when this click happens it just runs a function that holds our code document body classList toggle dark mode As you can guess we are selecting the lt body gt element of our webpage and saying check if this element has a class of dark mode if it doesn t add that class But if it already does remove the class OutputNotice what s going on under the hood Our dark mode class gets added to the body of our document when the toggle is clicked on which prompts all the values of the custom CSS properties used all over our webpage to get overridden with the new values in the dark mode class Clicking on it again removes this class which results in our initial global variables taking effect again Now let s take a peek at Hashnode com s implementation of their dark mode Notice it s basically the same but they re simply adding theirs to the lt html gt element still you get the idea and how to go about implementing this feature in your future or pre existing features ConclusionCongrats on getting to the end of this article As a side note I d like to point out a particular implementation I came across a while back in this tutorial the instructor wanted to implement an option for users to be able to select between color modes on a website light dark and blue mode so he had the initial style of the website copied into several stylesheets and manually edited each stylesheet to match the theme of choice and then used JavaScript to dynamically swap the stylesheet link to that of the users choice on click It worked as intended but thinking back there was something I found strange with the implementation when an option was clicked on there was a visible seconds delay before the new theme took effect and that had left me wondering why Knowing better now this delay was a result of the browser downloading the new stylesheet and applying it hence the slight delay As you can guess this is not very performant or friendly to the user s experience but you are free to experiment SupportIf you found this article helpful which I bet you did got a question or spotted an error typo do well to leave your feedback in the comment section And lastly someone might be somewhere struggling to implement a dark mode do well to share this resource and follow me for more And if you re feeling generous which I hope you are or want to encourage me you can put a smile on my face by getting me a cup or thousand cups of coffee below Ko fiPayPalPaytreonBuyMeCoffee 2021-10-17 14:15:51
海外TECH DEV Community How to use absolute path in ReactJs https://dev.to/emanuelone/how-to-use-absolute-path-in-reactjs-503i How to use absolute path in ReactJsAbsolute Path vs Relative Path Absolute Path is when you source for a folder or file from the root either where your system storage start from or where the project start from Relative Path is when you try to source for a file or folder taken into consideration where you are currently located in the project structure Steps to configure your React project with absolute path Create React AppAdd jsconfig jsonImport file with absolute path Create React Appif you already have react app to configure you can skip this stepnpx create react app app nameApp jsimport Button from components button const App gt return lt div gt lt Button gt lt Card gt lt Card gt lt div gt export default App Add jsconfig jsonin your project add jsconfig json beside package jsonjsconfig js compilerOptions baseUrl src exclude node modules build include src for typescript create tsconfig jsontsconfig json compilerOptions baseUrl src include src Import with absolute pathimport Button from components button const App gt return lt div gt lt Button gt lt Card gt lt Card gt lt div gt export default App 2021-10-17 14:15:33
海外TECH DEV Community Docker Quick Start https://dev.to/vmtechhub/docker-quick-start-1lb5 Docker Quick StartBefore talking about Docker let s first talk about Virtualization in general VirtualizationVirtualization is a way to utilize the underlying hardware more efficiently Do we really need virtualization In general yes If every single application requires a separate machine chances are that most of the time that machine will be underutilized and we will be wasting the hardware resources like CPU memory etc With virtualization many applications can share the same physical hardware A virtualization solution acts as a layer on top of actual hardware How does a system achieve virtualization It does so via a Hypervisor Hypervisor is a software through which we achieve desired virtualization There are two types of hypervisors Type aka bare metal because it runs directly on the hardware Type runs as an application on the host operating system Virtual Machines VMs Virtual machine as the name suggests is a machine with its own OS A VM emulates physical hardware An application running inside a VM doesn t know if it s running on the real machine or not hence the name Virtual Machine Many VMs can run on the same machine without knowing each other A virtual machine runs on the Hypervisor and accesses the underlying hardware through the Hypervisor In this diagram we see two different VMs running on the same machine using a Hypervisor VM has Linux and is running an application named App VM has Windows and is running two applications ーApp and App ContainerizationContainerization or OS level virtualization is an OS feature in which the kernel allows multiple isolated user space instances these instances are called containers A Container is like a box in which an application runs The container provides virtualization to that application The application doesn t know on which OS it is actually running for that application container is everything It is the container s job to provide libraries dependencies and everything else that an application needs for a successful execution The application runs within the boundaries of the container hence it is less dependent on the host OS And for the same reasons completely isolated from other containers running on the same machine What problems does a container solve PortabilityLet s suppose we re building an application from scratch So We find a machine We download all the required software their dependencies Then we install and configure everything Configuring a software or tool generally involves changing some config file on the OS or may be changing some network port etc Finally everything is up amp running on your dev machine Cool stuff Now how would you move this application along with its configurations to another machine Without any containerization tool or technology we would need to repeat everything that we did on our dev machine And if everything is scattered and not properly documented and managed we may easily miss an important config on the new machine In that case either the machine itself or some other application is screwed With the help of containers or VM we can just copy the VM or the container to the new machine Because apps are configured to run inside a container and nothing is actually installed on the host machine directly you move them as a package Packaging and DeploymentIn extension of the previous point as soon as you containerize your application it is ready to be moved to any machine To create a container for your app you tell the container everything about you app ーconfigs ports file system dependencies other s w dependencies etc The container becomes the runnable and deployable package Any machine which has the right container infrastructure will be able to run your container It is similar to Java classes once compiled you can run the same class file on any machine as long as it has the right JVM ScalingContainers promote microservices pattern There should be one service per container Under heavy load if you need another instance to share the load you just need to add more containers and your service is immediately scaled Dependency conflicts and clean removal of applicationsWithout containers dependency conflicts may arise as multiple apps may require the different versions of the same dependency Let s suppose A needs x version of Sybase and B needs y version of Sybase Let s consider another scenario ーIf you are uninstalling removing an app from your system chances are that you may forget to remove its dependencies which will remain there and eat the system s space Dependencies like these not just make the working difficult but also pollute the machine when you don t need them anymore In case of containers an app and its dependencies are packaged as a bundle So there is no dependency conflict Also instead of removing an app you remove the container So everything will be removed as a package which keeps a machine clean DockerLet s finally talk about Docker Docker website defines Docker as an open platform for developing shipping and running applications Docker is an application container which enables us to bundle an application and all its dependencies as a package so that it can be shipped anywhere and run on any machine It is written in Go language Under the hood a Docker container is simply a Linux process that uses Linux features e g namespaces cgroups seccomp etc Docker terminologyDocker client ー Docker client is installed on the client machine We run docker commands using docker client Docker daemon ー Generally installed on the same machine It listens for Docker API requests and does everything required for a docker container to run Docker registry ー A registry is a place where docker images are stored For instance GitHub is a registry where people manage their codebases In the same way docker images are stored in a docker registry A registry could be public like Docker hub or private Docker image ー An image is a read only template with instructions for creating a Docker container Docker container ー A container is a runnable instance of an image Difference between a Docker image and Docker containerLet s take an example of a Java class A class has some code which could be stored as a java file on a local directory or as a github project A class doesn t do anything on its own But when we compile and run a class file the same read only class becomes a runtime object an executable piece of code that does what it was coded for A docker image is just like a java file that has some instructions on what to do when you want to run a container And when we run a docker image via docker client docker creates a running container Just as we can create multiple objects of a single class we can create multiple running containers from the single docker image High Level WorkingThere s a nice diagram on Docker site which depicts the high level flow When we run a command to run a container from an image Docker checks if the image already exists on the system If yes it uses the image to run a container If no it goes to a registry to find and pull the image Docker downloads the image on the systemDocker runs the image and starts the container Useful Docker commands Docker architecture and key componentsDocker has a layered architecture Some of the key components in the order from low to high are as below runc libcontainer ー containerd ー Docker daemon ー Orchestration ー Here is a diagram which shows these components with a small description ーwhat it is and what a component does What happens when we run a container Feel free to checkout my blog 2021-10-17 14:14:50
海外TECH DEV Community Chess Pieces, Inheritance vs Composition https://dev.to/parenttobias/chess-pieces-inheritance-vs-composition-52j2 Chess Pieces Inheritance vs CompositionIn my last post I started discussing how this chess project has been an evolution that is allowing me to experiment with things in order to learn different approaches And that last post was pretty clean and easy as it was simply re thinking the HTML and CSS required to create a chessboard Rethinking Gameboards Toby Parent・Oct ・ min read javascript webdev beginners css This time things are a little less clear There is no right answer this time There are many ways to tackle this particular challenge and we ll work through a few of them to the one I finally went with Let me also say though I really enjoyed and appreciated the feedback and suggestions last time This is an evolving and growing project and your comments really give me some great ideas I don t claim to be an expert by any stretch I m still evolving along with this one The WhyWe are now looking at the chess pieces themselves and how best to create both the DOM and the javascript representations of them An easy option might have been to define a ChessPiece class and extend that for each one class ChessPiece constructor start this current start this domEl document createRange createContextualFragment lt div class chess piece gt lt div gt firstChild this to this to bind this to target this current target this domEl style gridArea target static toXY xLetter y gt return x ABCDEFGH indexOf xLetter y Number y One more specific piece derived from that oneclass Knight extends ChessPiece constructor start super start to target if this isValidMove target super to target else console log nope nope nope isValidMove target const start ChessPiece toXY this current const end ChessPiece toXY target return Math abs start x end x amp amp Math abs start y end y Math abs start x end x amp amp Math abs start y end y const bqKnight new Knight B yeah but he s not just a knight we need to add some custom classes bqKnight domEl classList add queens black and now we can use it as we likebqKnight to C console log bqKnight Now there is nothing inherently wrong with that approach classes work pretty well and for something this small I might not think twice If you look at that code it has some fun stuff going on a static method in the ChessPiece to attach it to the constructor itself and not its prototype the string to DOM node trick I picked up from David Walsh but it s pretty clean We define a class and we extend that for each unique piece The biggest change for each piece would be the isValidMove function as we would be tailoring that However toward the end of that we can see the problem with constructor functions and classes our constructed Knight is completely exposed Poor guy is a Knight without armor All his properties and methods are dangling out for all the world to see and to change willy nilly We simply jammed new classes right in without so much as a please and thank you There are other issues to using inheritance descendants are tightly coupled to their ancestors in the prototype chain making them brittle javascript doesn t do classes the way a class based language does prototypal inheritance is a subtly different route but by calling them classes we give a false sense of understanding The white box approach exposing the entire object is not the only downside to classes in javascript but it s a major one And that alone for me is a deal breaker Let s look at another way The HowWe can re use functionality in a couple of ways In the above example we use prototypal inheritance to define the ancestors the prototype chain But we can also use composition to build something that can draw from one or more other objects consuming the functionality it needs As we saw above implementing the inheritance route is pretty easy but let s see if we can move that to a composed functionality instead Rather than using classes at all we can use a Factory function for each piece Doing that we gain the hidden scope of the function and we return an interface object to that scope that defines a closure It s a closed private space that remains after the function that called it has returned keeping those variables it contains accessible by planned lines of communication Further with composition we can delegate This means if we like we can pull in some other object and tell that to handle some part of our main functionality In our case I d like the HTML bit to be handled by a delegate We ll call it generically Piece Here s how the implementation of a Piece factory function might look const Piece starting gt both the current position and the domNode are in a private data contained in the calling function s own scope let current starting const domNode document createRange createContextualFragment lt div class chess piece gt lt div gt firstChild domNode style gridArea starting Both domEl and to define our interface domEl returns a reference to the piece s DOM and to updates the piece s location in the grid let domEl gt domNode const to target gt current target domNode style gridArea target Finally what we return is an accessor into this private scope The internal values can only be affected via these two methods return domEl to And some functionality we might find handy later When we calculate the start end x y values for pieces to be able to determine valid moves But by defining it on the Piece we get this automatically when we include it as our delegate Piece toXY xLetter y gt return x ABCDEFGH indexOf xLetter y Number y export default Piece Now that s great we have all our DOM manipulation of the piece contained and we can simply call myPiece to C to update it in the DOM I like it Another aspect of composition is the re use and abstracting of functionality making things useful in other settings The moves available to chess pieces is a great example some move laterally any number of spaces some diagonally some move many spaces some only one But there are a few ways we could simplify those move options First we need to think about moves a little differently Up to now our chessboard grid is defined by chess notation A D and the like But the rules to moving are x y based that s why I added that Piece toXY function given a D that function gives back a x y pair Given a starting and ending point we ll get two x y coordinates back So as to the possible moves there are four generic rules we need to define Lateral start x end x or start y end y either the x or the y coordinate stays the same for lateral movement Diagonal The absolute value of start x end x is equal to the absolute value of start y end y xByN Given a number N the absolute value of start x end x must be equal to N yByN Given a number N the absolute value of start x end x must be equal to N That s it A rook s move is lateral a bishop s diagonal A queen is either lateral or diagonal A knight is either xByTwo and yByOne or xByOne and yByTwo The pawn is the only tricky one with different opening one or two xByOne movement only in one direction unless capturing en passant pawn promotion honestly I haven t even begun to think about any of that Further the rules I ve defined don t take into account whether a piece is in the path or not this was a simple experiment to see if I could fathom composition enough to implement the simpler aspects of it So all that said moves is a simple object literal Here s the moves js const moves in each I deconstruct the x and y for both start and end to make it easier to follow lateral x x y y gt x x y y gt x x y y diagonal x x y y gt x x y y gt Math abs x x Math abs y y in the byN rules we use currying to pass the allowed distance as the first parameter xByN num gt x x y y gt x x y y gt Math abs x x num yByN num gt x x y y gt x x y y gt Math abs y y num export default moves With that we ve defined all our possible moves We can make them more detailed when we implement them as with the Knight js import moves from moves js import Piece from Piece js const Knight classNames gt starting gt let current starting here s our DOM delegate const piece Piece starting const domNode piece domEl and internally we can modify the content of that DOM node We haven t broken the connection to Piece we simply add classes to that original domNode classList add knight classNames const isValidMove target gt we can use that static method to get x y pairs const start Piece toXY current const end Piece toXY target composed move functions the move function itself is defined by xByN and when the start and end parameters are passed we will get a true or false for each move method const moveX moves xByN start end const moveY moves yByN start end const moveX moves xByN start end const moveY moves yByN start end in order to be valid one of the two pairs must be valid return moveX amp amp moveY moveX amp amp moveY const to target gt if isValidMove target we need to keep this current as isValidMove uses it current target And then we delegate the DOM update to Piece piece to target else console log Nope nope nope And this is simply a passthrough function it exposes the piece s DOM node for consumption const domEl gt piece domEl return to isValidMove domEl export default Knight Note that in each Factory I am not exposing any internal variables at all I expose an interface which will allow me to communicate with the Knight in a predefined normalized way const bqKnight Knight queens black B bqKnight to C It works quite nicely and it hides away the data while exposing the functionality I will admit though that I m bothered by the repetition each of the individual pieces share a lot of the same functionality The only thing that is changing within each piece is its own isValidMove function but I can t for the life of me figure how to create a re usable to function like the one in the Knight above It should be possible in fact should be trivial that s the point of object composition Anybody got suggestions on that one 2021-10-17 14:13:51
海外TECH DEV Community How to Create Animated Toggle Switches with Just CSS and Implement a Dark Mode Feature https://dev.to/daveyhert/how-to-create-animated-toggle-switches-with-just-css-and-implement-a-dark-mode-feature-2e3d How to Create Animated Toggle Switches with Just CSS and Implement a Dark Mode FeatureA toggle switch as we know it allows us to choose between two opposite states such as an on off state whether it s turning on a light bulb or switching off a microwave toggle switches are everywhere because we use them daily It s no surprise then that digital toggle switches when implemented on a website gives it a more modern feel and facilitates micro interactions between users and the site Take Hashnode for instance it has an animated toggle that allows us to change the theme of the entire site from a light mode to a dark mode and vice versa You might have seen this or even fancier animated toggles on other websites as well and wondered just how these toggle switches are made and how these website themes are changed on the go because as a developer designer you ve got to admit It s a pretty cool modern feature to have on your own website and projects That s what we are going to be learning in this article by the end of this article you d have not only learnt how but also mastered the art of making toggle switches and implementing light mode dark mode PrerequisiteYou only need to have basic HTML amp CSS knowledge i e I shouldn t have to explain what input label width height etc are A text editor and browser of course if that wasn t obvious already You enjoy explanations geared towards Year olds Understanding CSS Just a Little BetterThe idea of creating a toggle switch with just CSS can seem really daunting at first when you think about it you d normally assume you needed a library or at the very least JavaScript for such a task and although you aren t exactly wrong as most people use those for creating theirs this is a somewhat trivia task that CSS can handle Before diving into our code I d like to shed some light on two particular features in CSS that some of us overlook but because our code is dependent on these features we need to talk about them for a second The first has to do with the input and label elements in forms We won t be creating any forms here but for illustrative purposes I m going to create a label and an input element with the type set to checkbox in our HTML document lt label gt A confused label lt label gt lt input type checkbox gt OutputSemantically we have created a label with an input element next to it by just looking at it in the browser you can easily tell that this label is meant for our checkbox and you could even style both to look related There s nothing wrong with that since clicking on the checkbox toggles its state to checked unchecked as intended But to that label itself it has no idea what it is doing in that document or that it is supposed to be associated to that checkbox input by appearance alone they might look related but programmatically they are unrelated so clicking on this label does absolutely nothing But CSS has an attribute that you can assign to a label to tell it what relationship it has with an input element and that is the for attribute and for this attribute to link a label to an input the input would have to have an id with the same value as the value assigned to the for attribute in the label So let s modify our code so you can see the effect of this link lt label for switch gt A Linked label lt label gt lt input id switch type checkbox gt OutputNotice that after setting the value of the for attribute in the label and id in the input to the same value switch when either the checkbox or label is now clicked the checkbox gets toggled as they now have a relationship established they are linked The second feature has to do with pseudo classes Now because most people confuse pseudo classes and pseudo elements as the same thing we need to establish the distinction between these before continuing Pseudo Element A pseudo element is simply a selector used to insert inject an artificial not present in the HTML markup content on the webpage and to style specified parts of an element A few examples are the before after placeholder first letter etc Note that they are declared with two colons i e but since we have no interest in them I ll explain no further Pseudo Class A pseudo class on the other hand is simply a selector that targets the state of an element and does a tiny bit more A typical example of this is the hover state of an element which means you want to apply certain CSS rules when the user hovers over the element with their mouse The interesting part is certain elements have their own unique pseudo classes an a link for instance has a visited state Google uses this on their search results where if you click on a link to visit a site and then come back to the search results the color of the link you visited would change from blue to purple And just like a link a checkbox also has its own unique pseudo class of checked and unchecked Note that the pseudo class is declared with a single colon sign i e That brings us to the most interesting part of these pseudo classes we can actually target and style other elements based on the state of a particular element using pseudo classes Let s go back to our label example and modify the order in which they appear so the input appears before the label lt input id switch type checkbox gt lt label for switch gt A Linked label lt label gt Now let s change the color of this label whenever the checkbox is toggled checked and then I ll explain further input checked label color blue OutputUnderstanding the codeinput checked We are simply targeting the checked state of our input element using the pseudo class and saying we want to do something when this element is checked This is an adjacent sibling selector meaning we want to target an element that is immediately next to the input element label Finally we are saying if the state of our input element changes to checked change the color of the label element from whatever initial color to blue Easy as pie right but there are two caveats limitations to using the state of one element to style another which was why we had to make sure the input was above the label You can t style a parent or root element based on the state of its child because CSS is a Cascading Style Sheet by nature meaning styles are applied from the root of the document top of the family tree downwards to nested children In otherward only children can inherit properties from parents but never parents inheriting from children Still confused think of CSS as a waterfall that only flows downwards from the top of a fountain you can t ask it to disrupt this flow by moving back up to change the style of an element based on a change in the state of a child element You can style an element based on the state of its sibling element but only if the sibling element is an older sibling i e the element whose state is to be used has to be an element that sits above the target element in our markup Using our example above if our label sat above the input we wouldn t be able to style the label based on the change in our input because the input is by order of arrangement a younger sibling to the label CSS will not carry styles upwards only downwards meaning only the state of an older sibling element element that comes before can affect a younger sibling element that comes after Now you understand CSS a little better with that knowledge you are ready to create a toggle switch using just CSS How to Create a Toggle Switch with Just CSS The HTMLSo let s begin with the HTML markup but because we need at least two icons to implement the animated part of the switch we are going to grab them off font awesome If you happen to be a total newbie with little experience using font awesome icons It s a library that gives you a collection of icons to use in your projects We will begin by linking our HTML document to this library to get that access The quickest means of doing this is by Googling font awesome cdn or using Add the gotten line of code to the head of your document just before the link to your CSS stylesheet That s all let s proceed with our HTML markup We ll start by recreating the input and label example we ve been using since but this time we ll put both siblings in a div container that acts as a wrapper and instead of putting an actual text in the label we will place two icons and a span as replacement for the label text lt body gt lt div class switch container gt lt input type checkbox id switch gt lt label for switch gt lt i class fas fa sun gt lt i gt lt i class fas fa moon gt lt i gt lt span class ball gt lt span gt lt label gt lt div gt lt body gt OutputThat s all the HTML we need for this switch but did you notice that when anything in the label tag any icon gets clicked it also toggles our checkbox like we are clicking on the checkbox itself Hopefully it doesn t look like magic because we already explained this behaviour earlier Hint The labels for attribute is linked to the inputs id The CSSWe ll start off by resetting our document and quickly centring everything in the DOM using flexbox margin padding box sizing border box body height vh display flex justify content center align items center Now to the actual code the switch container div that wraps the input and label is of little or no interest to us actually we are mostly interested in styling the label as a switch and using the input elements change in state to do our little magic So let s style our label before going through the code label display flex width px height px justify content space between align items center padding px background border radius px cursor pointer position relative OutputBecause a label is an inline element and we wish to give it a fixed width height we set its display to either in line block or flexbox I ve gone with flex so I can easily control the placement of the icons in the label by vertically aligning them in the center align items and then pushing them apart justify content Notice that the sun is not pushed to the end If you recall we have elements inside our label the two icons and the span element with a class of ball CSS is simply respecting the invisible span as it has no content to show itself because it s an inline element We then apply a little padding vertically left right to keep the icons from touching the edge of the label we proceed to give the label a dark background and a symmetrical radius of px so it looks just like a button tab and finally a cursor so it s obvious it is meant to be clickable But before leaving I throw in a position of relative It s of no use right now but we ll use it in a minute Let s move our focus to the icons label i font size px label fa sun color gold transition s label fa moon color fff transition s label ball display none OutputWe ve simply given both icons a size of px then changed their individual colors to gold and white respectively and because we plan to move these Icons in a second we give them a transition of s We then hid the span element from the DOM temporarily because we are about to do something cool and I don t want that to get in the way as a result the sun is freely pushed to the end Note Transition property allows us to smoothly change the values of an element s property over a given duration It s time for our first magic recall that when the label is clicked on it triggers the checkbox to be toggled We will now use that pseudo class state to animate the icons to move each time the input is toggled input checked label fa sun transform translateX px input checked label fa moon transform translateX px Outputinput checked label icons class Again we re using a pseudo class to target the checked state of the input and then saying when this input is checked target the next adjacent label junior sibling and do something to the icons inside that label transform translateX px Here we are using the transform property which lets you change the disposition of an element move rotate scale translate skew etc and then applying a translateX which is to move the element horizontally The moon is given px which is to move it to the left by px while the sun is to be moved to the right by deg Since we already set a transition duration they ll move smoothly using the provided time For the next trick we are going to make the moon disappear initially by setting its opacity to and only make it visible when the input is checked while the sun will be visible in its initial state but made to disappear when the input is checked label fa sun opacity input checked label fa sun opacity label fa moon opacity input checked label fa moon opacity Don t be confused by my choice of adding them as new CSS rules I simply want you to be able to follow the order of added effects and not get confused by too much code in your face OutputNote Opacity controls the transparency of an element completely transparent completely opaque visible Again our transition duration makes this whole change appear smooth and animated Now recall that we had a span with a class of ball next to our icons that we set to display none It s time for it to shine we are going to style it like a round ball and give it a position of absolute why Recall we gave the label element a position of relative We did that because when a child elements position is set to absolute it s pulled off its natural position and floats off in search of a parent element with a relative position to attach itself to So when we set the span elements position to absolute we pull it off the ground but still keep it in the labels bounding frame by setting the label to relative position This way the ball doesn t affect our icons but rather floats above them label ball position absolute display block width px height px top px left px background fff border radius transition s OutputAs it is a span inline we made it a block element added fixed with height and a top left property of px meaning the ball should be held by px from the top and left sides of the label holding it Then added a white background and made it circular using border radius You already know what the transition is there for we are going to move this ball when the input gets toggled input checked label ball transform translateX px OutputNotice we no longer see the moon That s because it s moving in the same direction as the ball so it s hidden behind it overlapping But that s not what we want so we will modify our moon so it is on the right initial its opacity still left at and then move it to the left when the input is clicked opacity still left at label fa moon transform translateX px input checked label fa moon transform translateX OutputWe are almost done with our toggle switch we ll change the background color of the ball and the label respectively when the toggle is checked I intentionally set the transition duration to be long so we could see the changes that were happening to our elements but now we ll speed it by setting every transition to s seconds and finally hide the input that is hovering over the label label transition s input checked label background ccc input checked label ball background input display none Change every previous transition from s to sOutputTo make our switch more lively let s throw in a rotation effect so the icons both spin out when toggled input checked label fa sun transform translateX px rotate deg label fa moon transform translateX px rotate deg input checked label fa moon transform translateX rotate Final ResultHurray We ve made a sleek animated toggle switch with just CSS and you ve learnt enough to be able to recreate any toggle switch you come across on the internet As a bonus I ll link to a second article where we convert this toggle to two fancier ones made with svg icons Now this article has gotten quite long and for that reason we re going to split it up and end with a cliffhanger here The rest of the article will focus on how to implement a dark theme or multiple themes on your pre existing websites projects or future ones The link will be provided below so also will a link for making two other variants of the toggle switch ConclusionIf you found this article helpful which I bet you did got a question or spotted an error typo do well to leave your feedback in the comment section Lastly someone might be somewhere struggling to make a toggle switch or implement a dark mode do well to share this resource and follow me for more And if you re feeling generous which I hope you are or want to encourage me you can put a smile on my face by getting me a cup or thousand cups of coffee below Ko fiPayPalPaytreonBuyMeCoffee Link to Second Article How to Implement a Dark Mode with CSS and Simple Lines of Javascript David Herbert・Oct ・ min read css javascript tutorial beginners 2021-10-17 14:09:04
Apple AppleInsider - Frontpage News Monolith TrueWireless Earphones Review: price isn't everything https://appleinsider.com/articles/21/10/17/monolith-truewireless-earphones-review-price-isnt-everything?utm_medium=rss Monolith TrueWireless Earphones Review price isn x t everythingThe Monolith TrueWireless Earphones compete with features and a lower price point but Apple fans should stick to AirPods Monolith TrueWireless EarphonesEver since Apple debuted the first set of AirPods third party manufacturers have attempted to recreate their magic Even though the Monolith TrueWireless Earphones have good sound and decent technology they are too close to AirPods in price to justify a purchase if you live within Apple s ecosystem Read more 2021-10-17 14:36:14
Apple AppleInsider - Frontpage News Apple considered making a cloud gaming service alongside Apple Arcade https://appleinsider.com/articles/21/10/17/apple-considered-making-a-cloud-gaming-service-alongside-apple-arcade?utm_medium=rss Apple considered making a cloud gaming service alongside Apple ArcadeApple allegedly considered launching its own cloud based gaming service similar to Nvidia s GeForce Now and Google s Stadia with a claim talks took place internally about an alternative to the device based Apple Arcade Cloud gaming services provide gamers with a way to play games with a high level of graphical quality by rendering gameplay in the cloud and streaming a live video feed to the user s devices It seems that at one point Apple considered joining the roster of companies providing the services to users In Sunday s Power On newsletter for Bloomberg Mark Gurman was asked if Apple was working on such a service In response Gurman suggested that Apple thought about it but hasn t gone through with the project Read more 2021-10-17 14:10:06
海外TECH Engadget Apple's new MacBook Pro chips may be called the M1 Pro and M1 Max https://www.engadget.com/apple-macbook-pro-m1-pro-m1-max-leak-145253589.html?src=rss Apple x s new MacBook Pro chips may be called the M Pro and M MaxLeaks are still pouring in just a day before Apple s quot Unleashed quot event kicks off According to MacRumors Bloomberg s Mark Gurman understands the chips for the widely expected and inch MacBook Pro models have surfaced in developer app logs under the names quot M Pro quot and quot M Max quot It s not certain Apple will use these names for its high end silicon but they suggest Apple won t go with MX or otherwise echo the naming scheme used for souped up A series chips nbsp Earlier rumors have hinted at two processors destined for the new MacBook Pros Both would include cores eight high performance two high efficiency An entry version would include a core GPU while the higher end model would pack a core GPU This roughly lines up with the M Pro and M Max naming schemes Other rumors have pointed to a direct sequel to the base M the M arriving sometime in early alongside a new MacBook Air Gurman also reiterated the changes he and others expect from the MacBook Pro redesign Both laptops would include mini LED displays with higher resolutions They may bring back welcome connectors like a MagSafe power port HDMI and an SD card slot You might also see support for up to GB of RAM and the death of the Touch Bar It wouldn t be shocking if Apple brought its Pro and Max naming schemes to computer CPUs If Apple is going to replace all Intel chips with in house processors as planned those clearer names might be necessary to help buyers understand performance differences between models If Apple does use the M Pro and M Max names that will speak volumes about its likely chip name strategy going forward 2021-10-17 14:52:53
ニュース BBC News - Home Westfield Stratford closed after fire in first floor shop https://www.bbc.co.uk/news/uk-england-london-58938824?at_medium=RSS&at_campaign=KARANGA floor 2021-10-17 14:24:51
ニュース BBC News - Home Ogbonna heads winner for West Ham at Everton https://www.bbc.co.uk/sport/football/58833947?at_medium=RSS&at_campaign=KARANGA everton 2021-10-17 14:52:56

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)