jQuery How do i apply CSS to selected text - javascript

I'm trying to apply CSS to selected text. I tried the following and it doesn't work. I'm using Firefox.
$(document).keyup(function(){
savedRange = selection.getRangeAt(0);
$(savedRange).wrap('<span style="color:red"></span>');
});
I also tried
savedRange = selection.getRangeAt(0);
$(savedRange).css('color', 'red');
I can do this with contentEditable using execcommand, but execcommand applies html tags rather then inline styles. ex: <font/> instead of style="font..". I need to apply inline style and not deprecated html tags. I would like to use the jQuery css() property to apply styles.

I'd recommend the CSS class applier module of my Rangy library for this. It works in all major browsers and for any selection. It will also toggle CSS classes on and off.
Here's an example from another question: How do I wrap a text selection from window.getSelection().getRangeAt(0) with an html tag?
Example:
<style type="text/css">
span.red {
color: red;
}
</style>
<script type="text/javascript">
var redApplier;
window.onload = function() {
rangy.init();
redApplier = rangy.createCssClassApplier("red", true);
};
function makeSelectionRed() {
redApplier.applyToSelection();
}
</script>
UPDATE
If using classes isn't an option, you could still use a variation on this, although it's slightly roundabout: you could use Rangy to apply a class, and then use jQuery to find spans with this class and add your CSS to each. Here's an example:
function makeSelectionRed() {
var randomCssClass = "rangyTemp_" + (+new Date());
var classApplier = rangy.createCssClassApplier(randomCssClass, true);
classApplier.applyToSelection();
// Now use jQuery to add the CSS colour and remove the class
$("." + randomCssClass).css({"color": "red"}).removeClass(randomCssClass);
}
jsFiddle: http://jsfiddle.net/z2mdw/2/

This question thread about handling saved ranges may help. It doesn't specifically tell you how to add CSS, but it will help you wrap your range, and then you can probably chain a .css() function on top of that.
var range = window.getSelection().getRangeAt(0);
var newNode = document.createElement("span");
range.surroundContents(newNode);
Then you should be able to apply css to that span.
EDIT:
To apply CSS to the range selection, you can do the following. See my working example on jsfiddle.
You can set the CSS style on the span node directly with Javascript:
// Get the selection range
var range = window.getSelection().getRangeAt(0);
// create a new DOM node and set it's style property to red
var newNode = document.createElement('span');
newNode.style.color = "red";
// surround the selection with the new span tag
range.surroundContents(newNode);
Or just surround the range with a span tag, and select that span tag with jQuery to use a nicer .css() syntax.
// get the selection
var range = window.getSelection().getRangeAt(0);
// create a new span node and give it an id 'testing'.
var newNode = document.createElement('span');
newNode.id = "testing";
// wrap the selection range with the <span id="testing"></span> node.
range.surroundContents(newNode);
// select that new node with jquery and use the jQuery .css() method to apply styles.
$("#testing").css("color", "green");
Obviously this javascript is not ideal for reuse as I hard coded an ID into the 2nd example, but hopefully you get the idea for use for your own needs.

Cant you do it with CSS alone?
http://css-tricks.com/overriding-the-default-text-selection-color-with-css/

Related

Is there a way to toggle between html tags with javascript?

I can easily toggle between classes using element.classList.toggle(). Thus, using bootstrap 4, for example, it's easy to change a class, and no extra css is necessary.
I was wondering if there is an equivalent method for toggling between different tags.
A use case would be toggle between "bootstrap 4" inline text tags https://getbootstrap.com/docs/4.5/content/typography/#inline-text-elements
Text decoration here is added by tags, and not by classes.
I did some previous research, and I've found other queries about toggle between divs. I also can figure out how to do it by creating a conditional statement.
But is there a way to toggle tags as easy as element.classList.toggle() using only javascript?
Swap from p to span and preserving attributes.
function swapTag(element, newTag) {
// New element with the desired tag
let newElement = document.createElement(newTag);
// Copy of all attributes
for(let attr of element.attributes) {
newElement.setAttribute(attr.name, attr.value);
}
// Replace
element.replaceWith(newElement);
}
// Create two elements
var parent = document.createElement("div");
var child = document.createElement("p");
// Assign some style
child.style.color = "red";
parent.appendChild(child);
// Before
console.log(parent.outerHTML);
// Do the magic
swapTag(child, "span");
// After
console.log(parent.outerHTML);

How to use Javascript to add multiple style properties to one element?

I've tried various renditions of this code to try and change a certain element for a coding exercise but non of them seems to be able to change multiple styling properties of an element on a button click. Would love some assistance. Thanks!
document.getElementById("Combo Style").onclick = function() {
document.getElementById ("More Text").style.fontSize.color = "50px , #BB65C5";
}
You can use cssText property but it will change the styling for the element completely
Style cssText Property
document.getElementById("myP").style.cssText = "background-color:pink;font-size:55px;border:2px dashed green;color:white;"
This will overwrite the existing css styling for that element , so make sure you included every needed property.
To achieve your expected result use setAttribute
HTML:
<button id="Combo Style">Change</button>
<div id="More Text">abcd</div>
JS:
document.getElementById("Combo Style").onclick = function() {
document.getElementById("More Text").setAttribute("style", "font-size:50px;color:red;");
}
http://codepen.io/nagasai/pen/AXVWwO
You need to grab the element by using id or any selector and use style property or css text property to apply css. Check the below code -
var element=document.getElementById("More Text");
element.style.fontSize="20px";
element.style.color="red";
element.style.background="blue";
You can also use cssText property, like -
document.getElementById("More Text").style.cssText='fontSize="20px";color="red";'
This will insert an inline style tag in the element with the csstext property.

How to get the computed style of the current element

I want to get the computed style of the current element using JS,
I am able to fetch the other attributes but am stuck at when it come to css.
here is my code , please help
document.addEventListener("click", function (e) {
e.preventDefault();
var dom_id = e.target.id.toString();
var dom_class = e.target.className.toString();
var dom_el = e.target.toString();
var dom_html = e.target.innerHTML;
document.getElementById('ospy_id').value = dom_id;
document.getElementById('ospy_class').value = dom_class;
document.getElementById('ospy_el').value = dom_el;
},
false);
Use following statement to get css of any element
document.getElementById(elementid).style.property
example:
document.getElementById("ospy_class").style.color
If you're using jquery (based on tags you're) you can do something along the lines of:
$("#elementID").css("color");
etc...... Documentation
It's not jQuery but, in Firefox, Opera and Safari you can use window.getComputedStyle(element) to get the computed styles for an element and in IE you can use element.currentStyle. The returned objects are different in each case, and I'm not sure how well either work with elements and styles created using Javascript, but perhaps they'll be useful.
please refer below url...
jQuery CSS plugin that returns computed style of element to pseudo clone that element?

createElement and pseudo classes

The css
div.online:last-child {
color:green;
}
div.offline:last-child {
color:green;
}
JavaScipt
var x=navigator.onLine;
var div = document.createElement("div");
if (x==false) {
var divContent = document.createTextNode("sorry, you're offline");
divContent.className="offline:last-child";
div.appendChild(divContent);
var k = document.body.appendChild(div);
} else {
var divContent = document.createTextNode("you are online");
divContent.className="online:last-child";
div.appendChild(divContent);
var k = document.body.appendChild(div);
}
here I am using .className to change the style of last word using the last-child pseudo class (so only offline and online are styled). I'm guessing there is a problem with the naming of the class in my js code.
Before I took this approach I used setAttribute, but I had little idea how to go about using pseudo classes using that. What class name (and / or code) should I be using?
First, you can't assign a class to a text node, only to an element. Assign the online or offline class to the div, not its text content.
Second, you can't directly assign a pseudo-class like :last-child. Selectors with such a pseudo-class in CSS are used to target elements that are the last child of their parent in the DOM tree.

How to change css properties of html elements using javascript or jquery

How can I change CSS from javascript.
I'm using jQuery-ui Dialog and I want to change the style of a DIV from javascript.
Thanks
Check out the jQuery documentation. If you want anything it will be there.
Anyhow, if you want to add styles to elements, you need to use the css function, which has a few variants.
$(selector).css(properties); // option 1
$(selector).css(name, value); // option 2
So if you have a DIV with ID of "mydiv" and you want to make the background red, you would do
$("div#mydiv").css({'background-color' : 'red'}); // option 1
$("div#mydiv").css('background-color','red'); // option 2
The first way is easier if you're setting multiple things at once.
If you want to check what a property is currently set to, you would use a variant of the 2nd option, just omit the value.
var color = $("div#mydiv").css('background-color');
Would make the var color be red if you already set it above, for example.
You can also add and remove classes, doing something like
$(selector).addClass(class_name);
$(selector).removeClass(class_name);
This answer works even without jQuery.
So you have something like this:
<style type="text/css">
.foo { color: Red; }
.bar { color: Blue; }
</style>
<div class="foo" id="redtext"> some red text here </div>
If you wish to change just some attributes, you can always find the element using
var div = document.getElementById('redtext');
function and then change the attached color style by
div.style.color = 'Green';
Making your red text appear in green instead.
If you want to change the class defined for the div to another style class, you can do:
div.className = 'bar';
making the div now use class bar, which makes your previously green text blue.
There are a couple of ways to manipulate elements styles using the jQuery framework. Take a look through the documentation related to CSS and changing attributes:
http://docs.jquery.com/Attributes/addClass#class
http://docs.jquery.com/CSS
Try this.This is jquery code.
$("myDiv").css({"color":"red","display":"block"})
If you are using vanila javacript,try this.
var myDiv = document,getElementById("myDiv");
myDiv.style.display = "block";
myDiv.style.color = "red";

Categories

Resources