Utilizing Jquery to Integrate Hashtags

I'm looking to implement a feature where any text I write starting with a # symbol automatically changes color to blue, and then returns to black once I hit the space key to end the text. I attempted to achieve this using the following logic within a contenteditable div:

    if (# is pressed) 
    hashtagging = true
    append "<span>" to div

    if (space is pressed and hashtagging is true) 
    hashtagging = false
    append "</span>" to div

However, this approach is not functioning as intended.

Answer №1

To achieve the desired outcome, consider implementing the following code snippet:

$(function() {

    var hashtags = false;

    $(document).on('keydown', '#myInputField', function (e) {        
        arrow = {
            hashtag: 51,
            space: 32
        };

        var input_field = $(this);
        switch (e.which) {
            case arrow.hashtag:
                input_field.val(input_field.val() + "<span class='highlight'>");
                hashtags = true;
                break;
            case arrow.space:
                if(hashtags) {
                    input_field.val(input_field.val() + "</span>");
                    hashtags = false;
                }
                break;
        }

    });

});

This code snippet monitors keydown events to detect the pressing of either hashtag or space keys, subsequently appending a span element with a designated CSS class for styling purposes. The decision to evaluate keydown events instead of keyup events is to ensure that the tags are inserted prior to the input being registered in the text field. It showcases the usage of a text field as the input mechanism, but feel free to customize it according to your requirements.

Answer №2

Check out this effective demonstration, where Sondre's solution is combined with Mr_Green's solution (Set the caret position always to end in contenteditable div) to move the caret to the end.

http://jsfiddle.net/344m4/1/

var hashTagList = [];

function logHashList(){
    hashTagList = [];
    $('.highlight').each(function(){
        hashTagList.push(this.innerHTML);
    });
    for(var i=0;i&lt;hashTagList.length;i++){
        alert(hashTagList[i]);
    }
    if(hashTagList.length==0){
        alert('You have not typed any hashtags');
    }
}
$(function() {

    var hashtags = false;

    $(document).on('keydown', '#example-one', function (e) {        
        arrow = {
            hashtag: 51,
            space: 32
        };

        var input_field = $(this);
        switch (e.which) {
            case arrow.hashtag:
                e.preventDefault();
                input_field.html(input_field.html() + "<span class='highlight'>#");
                placeCaretAtEnd(this);
                hashtags = true;
                break;
            case arrow.space:       
                if(hashtags) {         
                    e.preventDefault();
                    input_field.html(input_field.html() + "</span>&nbsp;");    
                    placeCaretAtEnd(this);
                    hashtags = false;
                }
                break;
        }

    });

});


function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

the combination of class and type functions as a jquery selector

<button class="actionButton default" type="submit"> Save</button> Can you select this button by both its class and type using a jQuery selector? I attempted the following, but it did not work: var saveBttn = $('.actionButton.default [ty ...

Unable to view new content as window does not scroll when content fills it up

As I work on developing a roulette system program (more to deter me from betting than to actually bet!), I've encountered an issue with the main window '#results' not scrolling when filled with results. The scroll should always follow the la ...

Creating dynamic images in Node.js using JavaScript without relying on HTML5 canvas

Hello everyone, I'm excited to be posting my first question on stackoverflow! Hey there, it's wabsol. I've been diving into the world of nodejs and loving every minute of it. I'm interested in creating a window and/or drawing an image ...

Is there a way to prevent javascript from automatically inserting tags when selecting text?

If you want to view the Fiddle Here Essentially, it's a text-highlighting tool that works almost flawlessly. The problem arises when it encounters tags like <p> or <br> within the selection. The JavaScript code seems to automatically in ...

Correcting the 1 pixel spacing issue in 3 containers each with a width of 33.333%

It is difficult to articulate, but I am noticing a 1 pixel line with 3 containers each having a width of 33.3333%. Unfortunately, this is not something I can change as it is part of the material-ui framework. <div class="container"> <div clas ...

Exploring JSON parsing using javascript?

I'm currently attempting to work through this webRTC example and have encountered an issue that appears to be minor in nature... The if statement consistently fails to return true, despite the fact that the console message indicates that the property ...

Achieving a 100% height sidebar that remains visible on the screen at all times in Bootstrap

Looking to achieve this specific layout: I want the left col-md-3 to maintain a consistent 100% height and always be visible on the screen - it's going to be a menu. The right side should function normally with scrolling capabilities. Appreciate any ...

javascript ondrag while self-pressing

Within this div, I have a series of p elements. My goal is to drag the selected element into the input field. Here's an example: var input = document.getElementById("test"); input.addEventListener('drop', function (event) { event.pr ...

"Exploring the world of Reactstrap: A

I am struggling to understand the documentation for Bootstrap and reactstrap as I have never used them before. For example, changing the Navbar color and background opacity has been a challenge because they require reserved keywords to be passed as props, ...

Best practices for storing non-reactive and static data in a Vue application

Welcome to the community! I'm excited to ask my first question here on StackOverflow. I am currently working with vue.js-v2 and webpack. My goal is to ensure that data remains immutable for child components, which are loaded through the vue-router. T ...

Adding items dynamically to a React-Bootstrap accordion component can enhance the user experience and provide a

I am retrieving data from a database and I want to categorize them based on "item_category" and display them in a react-bootstrap accordion. Currently, my code looks like this: <Accordion> { items.map((item, index) => ...

jQuery body background changer/utilizer

I am currently developing a website that requires the functionality to switch between background images with the ability for users to navigate through them using back and forth arrows. Each background image should have a unique dynamic description associa ...

Unable to retrieve the present aria-pressed value using the .attr() method

Currently, I am utilizing a bootstrap toggle from this source: https://codepen.io/aanjulena/pen/ZLZjzV The main function of this toggle is to reskin a button. When the status is "on," the aria-pressed attribute is set to true, and vice versa. Here is an e ...

I'm curious, are there any html rendering engines that can display text-based content using curl-php?

When utilizing PHP cURL to interact with webpages, I often find myself needing to use regular expressions if the page contains AJAX and JavaScript elements. Does anyone have any recommendations for rendering HTML pages and extracting the text-based render ...

unique map customized in a separate browser window

Attempting to complete the code provided here but encountering issues as a novice in java-scripting. It seems like the map is not loading correctly. A new tab and text are generated when DIV is created. Seeking assistance on how to open a custom map in a ...

How can I generate a list of JavaScript files to be included in a template for both production and development environments using Grunt?

I need a way to organize a list of JavaScript files in one central location, either within gruntfile.js or an external JSON file, and then dynamically implement it into a template for both development and production environments. List of JavaScript files: ...

What is the best way to extract the value from a Material UI Slider for utilization?

I am looking to capture the value of the slider's onDragStop event and store it as a const so that I can use it in various parts of my code. However, I am unsure about how to properly declare my const sliderValue and update it. Any guidance on where a ...

Creating Test Cases for Service Response Validation

I am currently attempting to unit test an API within my ngOnInit method. The method is responsible for making a call to the service in order to fetch details. If the details are not undefined, an array called 'shoeDataResponse' of type *shoeData ...

Creating dynamic routes in express to enable flexible and customizable paths

Exploring the dynamic usage of paths in Express has been on my mind. Specifically, I have been employing lodash to locate a path in a separate file using regex methods. routes.js const json = require('./routes.json') const _ = require('l ...

Using a wildcard (*) to select elements with JQuery

I'm just starting to learn about JQuery and could use some help. I want to select multiple elements but I only know part of their Ids: for example: <div id="element32422455">Some content</div> <div id="element68475124">Some content& ...