Share Selected Text with JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up friends hope you are doing well today we are using javascript in order to implement this feature which allows the user to easily share selected text in this case to Twitter but could be of course to any social media this feature is quite common especially in blog site and it helps websites gain exposure grow traffic increase search engine rankings and all the good stuff I hope you guys will enjoy this video and get some value out of it don't forget to share like subscribe and without further ado let's go so this is our starting point in the project folder I've created three files they index dot HTML style dot CSS and the main dot J's files in the index dot HTML file I typed some basic html5 boilerplate code inserted the title share selected text and linked the external files to the document they found awesome icons and the style dot CSS and main dot J's files both of them are currently empty also note is that instead of placing the script element in the body right above the closing body tag I placed it in the head using the defer attribute and we can now proceed to defining the body markup all we need here is basically some dummy content so let me paste and quickly go through everything will be contained within a container an h1 heading and h2 subheading and H R element in order to draw a horizontal line separating heading and content and a div containing a few paragraphs with lorem ipsum text notice that at some point in the second paragraph here we are I've added some English text in order to make testing a bit easier for those of us who don't speak Latin so this could be for example some article in a blogging website and now let's add the button which will allow the user to share the selected text we will only add one button here but could be a group of buttons allowing the user to share selected text to multiple places or even enabling user to perform other actions with selected text such as copying to clipboard or converting selected text to speech so that user can listen to it actually this could be interesting topics for future videos we'll see now the purpose of this button is to allow the user to share selected text to Twitter so let's add the corresponding font awesome icon as its content and finally for easier access let's add an ID to the pattern Twitter share button although in this specific case it's not necessary since we only have one button in our project notice that the pattern is a direct descendant or a child of the body and eventually it will be absolutely positioned relative to the body okay let's open the project in the browser for this purpose I'm using the live server which is a Visual Studio code extension so this is what we've created up to this point and let's add some styling with CSS styling is not the main objective of this video so let me paste and quickly go through I will of course include a link in the description to this project we start by resetting padding and margin to zero as well as pock sizing to border box for all elements some basic styling for the body this part is completely irrelevant to the main objective just adding some basic styling for the dummy content element some padding for the container own size and margin for headings and we also style the horizontal line as well as the paragraph element and by the way a while ago I've created a video explaining in detail how to use the linear gradient CSS function feel free to check it out now regarding the share pattern again some basic styling but what's most remarkable in my opinion is its positioning so the button is absolutely positioned relative to the body or starters I placed it to the top left corner although this is not really necessary since it will be repositioned each time before it is displayed that index is also defined just in order to ensure that it will be on top of the content and its display property is set to none so this is the result with CSS styling button is currently not displayed but it will comment this out here it is also not is that on however we reverse color and background color we also set pointer events to none for icon elements inside the share button since we are only interested in events over the parent element the button and finally I've created this button entrance animation so that button will zoom in whenever the button entrance class is added to it now this is of course not necessary and actually one might argue that there shouldn't be an entrance animation since text is selected instantly so this is just a matter of preference I am NOT adding an exit animation since there could be some weird implications for example in the case we are user quickly select and unselect text and some styling for smaller screens okay let's proceed to actually implementing the feature to share selected text we first need to decide which area will allow for selectable text could be the entire body or we could start being a bit more specific by setting the container deep to be a valid selectable text area or we could narrow it down even more to the main content or even to each paragraph or some of the paragraphs now for this example let's set this part to be a valid selectable text area as well as the h1 heading or these purpose we will add the selectable text area class to each element we want to set as selectable text area notice that we didn't use this class in CSS styling it will only be used in JavaScript and some people prefer somehow distinguishing pure JavaScript classes perhaps by adding a jes graphics just a matter of preference you choose your style and try to be consistent and I think we are set let's move on to JavaScript for starters let's store selectable text area elements as well as the Twitter share button into variables for easier access here we are notice the use of the query selector all method in order to select all elements with the selectable text area class I suppose I could use fluid here since this is now a list containing all selectable text area elements however I prefer singular and Twitter share button represents the Twitter share button element let's first take care events over the selectable text area elements for these peoples we can use therefore each method in order to go through each element of selectable text area list and at the event listeners we want to each element we are only interested in a mouse up event since this is the point where we want to check whether text was selected and if yes to display the share pattern so whenever there is a mouse up event over a selectable text area element we want to call the selectable text area mouse up function we will implement this function right now and by the way note that this would also work on touch screens since touch devices also support classic Mouse events although we could optimize with touch events this is beyond the scope of this video and let's proceed to implementing this function on a mouse up over a selectable text area we want to retrieve what the user has selected as far as any textual content all these purpose we can use the get selection method over the window object which returns a selection object representing the range of text selected by the user we can get the actual selected text by telling the selection into a string we can do this by using the tostring method over the selection and let's also trim the result in order to remove whitespace from both sides of the string and the lads console.log selected text in order to see what we get yeah we are all these is selectable text area and let's open dev tools we'd have 12 so if I select the first two words lorem ipsum I'm still holding the mouse down I'm releasing it right now yeah we are we get the text if I select this text over here and release the mouse now again we get the text if I just click we get an empty string if I select this part recall this is not selectable text area and I release nothing happens however this is selectable text area and if I release the mouse we get the text very nice if I select an empty space we get an empty string now just out of curiosity let's see what happens if a non core element text is selected so for example let's include the word libero within an a tag and if we select this part which includes the anchor element we can see that anchor text is normally treated as text similar behavior would occur if this was button text so again if we select this part which includes the button yeah we are okay but what if we had an image so let's add an image over here and see the result in this case an empty space is added in the place of the image however this behavior is not the same across all browsers for example I also tested for Firefox and in that case they add attribute text is added instead okay let's proceed so if text was selected and one way to check this would be by checking whether the length of selected text string is greater than zero so if selected text dot length and in this case we want to display the share button so let's set display property of Twitter share button to block and if I select some text indeed the button is displayed however let's be a bit more thoughtful regarding the positioning of the button and let's position it where the mouse up event occurred we can get the mouse up event coordinates by using the event dot page X and event dot page Y properties respectively note that this returns the position of the mouse in pixels relative to the document at first I tried using the event dot client X and client Y properties which however returned the position of the mouse in pixels relative to the viewport so it only worked as intended if no scrolling was involved otherwise I didn't get the intended behavior and now we can reposition the share button before displaying it by setting its left property to X but this is just an upper so we could concatenate or alternatively we could use template literals and similarly we can set the top property - why pixels much better but I would prefer to move it a bit further to the left and to the top so if width and height for the button is 40 pixels let's move it 20 pixels to the left and 50 pixels to the top nice but instead of hard-coding values here let's get the buttons width and height and do the calculations I will paste this part in order to save some time so for Twitter share button width we use the window object method get concluded style in order to get the width of Twitter share button this will return the width followed by the letters P X and in order to remove the last two letters we use the slice method alternatively we could use the substring method and finally we convert the result to a number so that it can be used in the calculation here similarly for the height so let's replace 20 here with Twitter share button width times 0.5 and 50 with Twitter share button height times 1.25 and finally let's also add the enhance animation by adding the button entrance class over the Twitter share button and this is what we get you can of course define your own rules for positioning the button and let's check for example how a couple of other websites treat this option this is set codings blog it is not a programming block cell Gordon is an author into the field of marketing / inspirations large creativity / thinking out of the box etc so if we select some text we can see that positioning of share buttons is quite similar to what we did nice and let's also check how the medium website handles sharing options so by selecting some text sharing options and by the way it's not just sharing but let's call it sharing options are positioned in the middle of our selection if our selection extends to more than one lines then sharing options are positioned in the middle of the first line where selection was initiated if our selection extends to more than one paragraphs then we don't get any sharing options so it is up to you to decide how you want to position sharing options my only suggestion would be to try to keep it practical okay let's continue with our project we now want the sharing button to go away when text is unselected for this purpose we want to listen for a mouse down event over the entire document and whenever there is a mousedown event we want to call that document mousedown function and let's implement this function right now so in this case we expect any selected text to be unselected and therefore we want to set the display property of the button to none and to also remove the button entrance class and we also want to ensure that the selection object is now empty we can do this using the empty method over the selection object this is equivalent to using the remove all ranges method nice however we don't want this procedure to take place upon every mousedown event in the document we only want it to happen if share button is currently displayed you and we also want to ensure that event target was not the share button itself because in this case button would disappear before the click event was triggered okay let's check the result by selecting some text button shows up and on a mouse down event anywhere in the document it did button goes away now one each case I discovered is the case where I select some text move away from selectable text area and release the mouse as expected share button is not displayed since mouse up or cared beyond the boundaries of selectable text area however if now I click on the selected text and release the mouse we can see that despite the fact that text was unselected share button is displayed and this is happening because on Mouse up there still seems to be text selected one way to get around this would be to include the mouse up handling into a set timeout method with zero delay so let's check the result okay we didn't break anything and now I'm selecting some text moving away from selectable text area and releasing the mouse and now if I click on selected text we can see that share button is not displayed and this was the intended behavior excellent all that remains now is to implement the share to Twitter functionality upon a click event over the share button so let's quickly do this and let's start by adding an event listener for a click event over the Twitter char pattern and in this case we want the Twitter share button click function to be executed we will implement this function right now so this is the general Twitter share URL of course not all query fields are necessary so let's start forming the URL by storing the various parts in two variables let's add this part into a variable called Twitter share URL next let's store the selected text into a variable called text and let's set URL to be the current page URL and let's add some random hashtags and via let's add my Twitter username Oh dink journey unfortunetely coding journey was already taken and all that remains now is to use the open method over the window object and assemble the general Twitter share URL for this purpose I'm using template literals and I will just paste this part since everything is quite straightforward so let's save and check the result let's share this part here we are notice that text is initially highlighted so that we can easily modify it here is the URL the hash tags and the username also notice the Twitter share URL we just assembled which is of course URL encoded very nice now it would be better to encode text before adding it to the URL since it could contain characters which could mess things up such as a hashtag so let's use the encode URI component global function and let's do the same for URL okay let's make sure that everything still works fine very nice now if we wanted more flexibility in forming that default to it for example instead of the word via we might wanted to use the word by here well in this case we could include everything in the text field and let's quickly do this let's copy this line and comment it out we remove this part since everything will be included in the text field after the text let's add the username and let's say by at I think URL encoding for the ad character would be percentage sign and 40 however it will not cause any problems so let's keep it like this next let's add the hashtags this will be a bit tricky first let's split the string into an array notice that separator is koma with an empty space so up to this point we end up with an array containing the hashtag words and let's use the map method in order to go through each hashtag word and add the URL encoded hashtag symbol and finally let's join array elements into a string using an empty space as separator and we are done with hashtags and let's also add the URL okay let's check the result here we are notice that now all content is highlighted since now everything is considered to be text so this is how you can modify the default to it we can also of course specify whether we want this to open in a new window as well as the features for the new window or these papers we should define the second and third parameters for the open method and let's use this example which is a bit shorter second parameter is a name for the window let's name it share on Twitter and third parameter is the features for the new window let's use a variable for this purpose yeah we are okay let's check the result here we are and of course we could position the window anywhere we wanted however to be honest I prefer the default behavior anyway before defining the second and third parameters for the open method and guys I think we are done let's actually tweet something in order to celebrate let's do it this and let's open Twitter yeah we are tweeted looks wonderful doesn't it I think this tweet will get me to at least 10k followers in the next few hours let's see I really hope you enjoyed this video and got some value out of it if you did please hit the like button and share it with anyone who might be interested also don't forget to subscribe if you want more or any questions suggestions or just say hi you can use the comment section below till next time keep coding keep improving and enjoy the journey take care bye
Info
Channel: Coding Journey
Views: 5,188
Rating: undefined out of 5
Keywords: Share Selected Text with JavaScript, Share Selected Text, how to share selected text, share to twitter with javascript, share to twitter with js, share selected text javascript, share selected text js, share text-selection, share text selection, sharing selected text, sharing selected text javascript, how to share to twitter javascript, how-to, html, css, javascript, ui, ux, tutorial, web tutorials, web development, coding, front-end tutorial, coding journey, web development tutorial
Id: HOrViIclSjw
Channel Id: undefined
Length: 29min 12sec (1752 seconds)
Published: Thu Sep 12 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.