Need to remove bold formatting? Try this compact WYSIWYG editor!

Hello Stack Overflow community,

I discovered a method called str.bold() that wraps text in <b></b> tags, which is perfect for a small WYSIWYG editor (I understand there are many open source solutions available, but I wanted to learn by creating my own).

However, I am facing an issue with unbolding the text.

Here is what I have tried so far: http://jsfiddle.net/Kxmaf/178/

I am aware of

editor.execCommand('bold', false, '');
, but it produces different HTML results in each browser. I specifically need only <b></b>, <i></i>, and <u></u> tags.

Any assistance would be greatly appreciated :)

Answer №1

Have you considered the idea of iterating over a chosen string using JavaScript while pressing a particular style button? By storing various tags like , , ... in an array, you could cycle through the specific string that has been selected. This way, you would be able to update the appearance of the style buttons once any of the tags are detected, indicating to the user which style is currently active. To revert back to the original text, simply iterate through the string again and remove the tags accordingly.

Answer №2

When working with user selections that span paragraphs, it's important to handle them properly. An example of this scenario is shown below:

<p>One <b>t|wo</b></p>
<p>Thr|ee</p>

To manage this situation effectively, you must enclose all text nodes and partial text nodes within the selection in <b> tags while preserving any existing bold formatting. This task can be complex, but tools like document.execCommand() or popular WYSIWYG editors simplify the process.

Many browsers support switching between style modes, allowing users to apply styles using elements like <b>, <i>, or <span> with style attributes. By utilizing commands like "StyleWithCSS" and "UseCSS," you can toggle between CSS and non-CSS versions accordingly, as demonstrated in the code snippet below:

try {
    if (!document.execCommand("StyleWithCSS", false, useCss)) {
        // In older browsers, switch to UseCSS
        document.execCommand("UseCSS", false, !useCss);
    }
} catch (ex) {
    // Handle exceptions for unsupported commands in IE
}

If you prefer using CSS classes instead of inline elements like <b>, consider leveraging the CSS class applier module available in the Rangy library.

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

Error message: Iframe chrome encountered a Uncaught DOMException when attempting to access the 'localStorage' property from 'Window': Document does not have permission

I recently developed a JavaScript widget that utilizes localstorage to set and retrieve properties of the window. Upon opening this widget in Chrome, I encountered an error message: Uncaught DOMException: Failed to read the 'localStorage' prop ...

Unexpected behavior encountered with JQueryUI modal functionality

Today marks my first experience with JqueryUI. I am attempting to display a conditional modal to notify the user. Within my ajax call, I have this code snippet: .done(function (result) { $('#reportData').append(result); ...

Record the cumulative amount computed using an asynchronous callback

If I use code similar to the one below, I am able to obtain the total byte size value every time a file is added. How can I log out only the total files size after it has been calculated in the fs.stat callback? var fs = require('fs'); var to ...

A particular character is displayed exclusively in a text box using either jQuery or JavaScript

Text Box <input id="txtbo" type="text" value="CAN'T TOUCH THIS!" size="50" /> Solution Using jQuery or Javascript: var readOnlyLength = $('#txtbo').val().length; $('#txtbo').on('keypress, keydown', function(even ...

Learn how to continuously update the current timestamp in PHP using jQuery or JavaScript every second

I am currently developing a PHP cart timer script that utilizes PHP along with jQuery and JavaScript. By using the set-interval function, I am able to continuously retrieve the current time-stamp in PHP. Once the first product is added to the cart, the t ...

Need help with creating a new instance in AngularJS? Unfortunately, the save method in CRUD is not getting the job done

Whenever I attempt to create a new task, nothing seems to happen and no request is being sent. What could be causing this issue? How can I go about troubleshooting it? Take a look at how it appears here Check out the $scope.add function below: var app ...

Trigger AngularJS functionality upon the completion of loading a Partial routed by Express

I'm fairly new to AngularJS and recently ran into an issue that's been keeping me up at night... Our application is built on node.js and express, with all partial routing handled by Express. The problem I'm facing is this: Whenever I load ...

Encountering Err_Connection_Refused while working with MVC WebAPI 2 and AngularJS

Seeking guidance on WebAPI, AngularJS, and .NET Authentication, I am currently following a tutorial mentioned HERE. The tutorial is brief (~under 10 mins), but I encountered an error stating Failed to load resource: net::ERR_CONNECTION_REFUSED. Typically, ...

Leveraging the power of Promise creation

I am facing an issue where I am trying to utilize the getPromise function with various URLs in order to obtain different promises, but encountering undefined values in the success function of the second promise. var http=require('http'); var URL ...

Creating Angular Custom Form Validation and Custom Directives

I recently created a custom validation directive and applied it to the form element like this: <form myValidations> app.directive('myValidations', function(){ return{ //require: 'ngModel', note its commented out link: f ...

As I iterated over the Vehicles API data, I encountered an issue while trying to access specific Vehicle information. I received an error message stating "Cannot read property 'id' of undefined

Exploring the realms of Angular, with some experience in older versions, I find myself faced with a challenge involving two APIs - "/vehicles" and "/vehicle/{id}". The process involves fetching data from "/vehicles", iterating through it to match IDs, the ...

The assigned type does not match the type 'IntrinsicAttributes & { children?: ReactNode; }'. This property is not assignable

I have been struggling to resolve this issue, but unfortunately, I have not found a successful solution yet. The error message I am encountering is: Type '{ mailData: mailSendProps; }' is causing an issue as it is not compatible with type &apos ...

What is the functionality of this JavaScript code after the "if" statement?

I am having trouble understanding how this code works, especially after the if(y in hash) statement. I don't see any values being pushed into hash initially. Can someone explain what happens behind the scenes and the significance of y in hash? var ...

Tips for Retrieving Information from Firebase in an Angular Application

I am facing an issue with my code where the ngFor directive is not working as expected when I use read_CheckOuts to return data from the database. Below are snippets of my code: crud.service.ts import { AngularFireDatabase} from '@angular/fire/datab ...

Having trouble transforming the JSON object into a usable format

Although I'm still getting the hang of JSON, please bear with me if this seems like a rookie mistake. My approach involves sending a query to a local file that performs a cURL operation on an external site's API and returns a JSON object. Due to ...

Accessing JavaScript results in PHP

Hello everyone! I am working on creating a dropdown menu for selecting time using JavaScript to get the computer's current time. My goal is to have an output that automatically selects the option in the dropdown if it matches the computer's time. ...

Having issues with the Email type in the JQuery Validation Plugin?

Recently, I set up a Grunt file to consolidate all my libraries and code into a single JS file for inclusion in my website. However, after adding the JQuery Validate plugin (http://jqueryvalidation.org/), I noticed that it's not working as expected. I ...

Implementing a loading animation effect using AJAX that requires a loop delay and sleep functionality

My jquery ui dialog is loaded via ajax with a partial view from the server. Initially, the dialog opens as a dialog-ajax-loader and then animates/grows to fit the content once the call returns. The issue arises when the dialog content gets cached or the a ...

Is there a way to detect changes in a Service variable within an Angular component?

One of my components contains a button that activates the showSummary() function when clicked, which then calls a service named Appraisal-summary.service.ts that includes a method called calc(). showSummary(appraisal) { this.summaryService.calc(appraisal ...

Socket.io allows us to broadcast messages to all users connected to the server using the "io

I've set up a MEAN app using npm socket.io with expressjs and btford.socket-io on the client side. angular.module('myApp',['btford.socket-io']) .factory('socket',function(socketFactory){ return socketFactory() ...