Manipulate highlighted text with Javascript - javascript

HI,
I'm trying to develop some code in Javascript that adds highlighted text to a class. What I want to achieve with this is the ability of text highlighting with a custom color.
I want it to kind of look like the following:
window.getSelected = "<span class=\"highlighted\">" + window.getSelected + "</span>"
after the above code is executed the selected text's background is surrounded by span tags.
thanks,
fbr

You'll want to look into Range Objects, there is a good summary here:
http://www.quirksmode.org/dom/range_intro.html
Browser compatibility will be an issue, but basically, you can get the current selection in the way you suggest, then convert it into a Range, and use the methods of the Range object to find and split the existing DOM nodes, and insert your own <span> tag containing the selected text.
It's not entirely trivial, and involves getting into serious DOM manipulation, but it's a rewarding subject to get your head around. Enjoy!

If you are talking about styling native selections, use ::selection and ::-moz-selection in CSS.
::selection {
color: ...;
background-color: ...;
}
::-moz-selection {
color: ...;
background-color: ...;
}
Alternatively, if you want to highlight an arbitrary element with a class:
CSS
.highlighted {
color: ...;
background-color: ...;
}
JavaScript
yourElement.className = "highlighted";

excuse my english, do you mean adding a class to a text?
function changeClass (elementID, newClass) {
var element = document.getElementById(elementID);
element.setAttribute("class", newClass); // This is for good browsers
element.setAttribute("className", newClass); //For IE<
}
leave all lines, its harmless if you do that way.

If you are using the jQuery framework you can try with the following code:
var your_color = 'yellow';
$('.your-class').css('background-color', your_color);
If you're not using it I highly suggest you start; it makes things a lot easier, it's very stable and it's used by many popular websites including google and stack overflow itself.

Related

Serialized and deserialize HTML style tag with CSS

What I'm trying to do:
Save/copy HTML snippet in one place, paste it in another place and have it de-serealized into an analogous DOM
How do I do serialization now
Call element.outerHTML on a container element
I've also tried using new XMLSerializer().serializeToString(element) with the same result
The issue
When I serialize style nodes that contain the css like:
.a > .b {
color: red
}
They actually get serialized like
.a > .b {
color: red
}
Which is not a valid CSS and so does not get parsed properly.
The problem with greater sign is the only one I observe, but it makes me wonder about other potential serialization issues.
Question: How do I get serialize the style nodes in a way that does not break CSS in them?
So it seems that this has to do with creating the style node dynamically on a new document.
The easiest reproduction is as follows:
const doc = new Document()
const style = doc.createElement('style')
style.textContent = '.a>.b { color: red; }'
console.log(style.outerHTML)
Which yields <style>.a>.b {color:red}</style>
It seems that being part of actively rendered document/or just generally being added to a document and not just created using it has some side-effect on the style node, which causes it to be serialized properly though. So now I do the following instead as a workaround, which is a bit ugly but works:
const doc = new DOMParser().parseFromString('<html><head></head><body></body></html>', 'text/html')
const style = doc.createElement('style')
style.textContent = '.a>.b { color: red; }'
doc.body.append(style)
console.log(style.outerHTML)
doc.body.removeChild(style)
Which produces an appropriately serialized <style>.a>.b { color: red; }</style>
Now this solves my problem, but I'd still really like to understand what is happening here in more detail (e.g. what is the side-effect exactly and how/when is it triggered), so would appreciate comments on that!

How to change colour of text when using document.getElementById("id").innerHTML

I am trying to change the text of a span to something else when a particular event occurs. I am doing this as :
document.getElementById("usernameError").innerHTML = "**Message";
I want to display the same in a different colour. Any idea on how to do that?
Much appreciated!
You could always just put the message in a span and put a style attribute on it. This should do it:
document.getElementById("usernameError").innerHTML = "<span style='color: red;'>**Message</span>";
As you can find in the Mozilla Developer Network, you can use HTMLElement.style property to change any style on the element.
So you can do something like this to colour it in red:
document.getElementById("usernameError").style.color = '#d00'
A more future proof and reusable solution would probably be to add a class to either the current element or the span element, depending on your requirements:
document.getElementById("usernameError").className = "color-red";
Or working off Erics solution:
document.getElementById("usernameError").innerHTML = "<span class='color-red'>**Message</span>";
Then in your CSS:
.color-red{
color: #F00;
}
You could obviously also add diff colours and attribute in a much more maintainable way like this.
NOTE: className Returns A String, representing the class, or a space-separated list of classes, of an element.

Proper way to author Jquery plugins with style rules

I have been long battling this, and I would like to know if any others have feedback. I am about to make a customized library for building web apps quickly, and I want to make sure I use the right approach. I WANT to use this method:
$.fn.someSlider = function(){
var coreStyle = '.slider ul { white-space: nowrap; } .slider ul li {display: inline-block}', coreStyleTemplate = '<style><\/style>';
}
But I feel like hard coding the base CSS into the widget is always frowned upon - instead I see SO users recommending the use of CSS style rules instead of this option. I really really really want that 'it just works' feel, and having to force my users to use a separate style sheet just to get my plugins working... well is annoying!
Just to clarify: I would like to include all base style rules needed for the widgets proper/base functionality to be included inside the script. The user would easily modify the base look of the widget by writing a style rule in their own style sheet.
Example:
Instead of having to look through all the base styles trying to find the font color like this... .slider {display: inline-block; color: #000; someotherconfusingrule : blahblah; }
The user simply starts a new rule with the classes name/selector being used - and then just write the changes to make to the default script styles
They would just write
.slider {color: #000};
Thanks for the help in advance SO!
Nice question! Although I'm not sure what the preferred solution to this would be, I was thinking of the following approach:
Use a IIFE to define your jQuery plugin and enable you to define some private, global variables and functions.
$.fn.pluginName = (function() {
return function() {
...your regular plugins code...
};
}();
Define your plugins CSS as a list of style rules in your plugins code
var rules = [
'.box {' +
' width: 100px;' +
' background-color: #f99;' +
' margin: 10px;' +
' padding: 10px;' +
' font-family: Helvetica, Arial;' +
' text-align: center;' +
'}'
];
Create a private variable that remembers if your stylesheet has already been added to the document
var styleSheetExists = false;
Create a private function that creates a stylesheet using the style rules above and that adds it as the first <style> element in the <head> allowing the user to override styles in their own CSS. See http://davidwalsh.name/add-rules-stylesheets for a good tutorial on how to do this properly
var createStyleSheet = function() {
var style = document.createElement("style");
style.appendChild(document.createTextNode(""));
$('head').prepend(style);
for (var i = 0; i < rules.length; i++) {
style.sheet.insertRule(rules[i], i);
}
};
The first time your plugin is applied to an element check if the stylesheet has already been created and if not create the stylesheet.
var $elements = $(this);
if (!styleSheetExists) {
createStyleSheet();
styleSheetExists = true;
}
$elements.each(function() {
$(this).addClass('box');
});
return $elements;
See http://codepen.io/ckuijjer/pen/FkgsJ for this example. It creates a jQuery plugin called box which simply adds the class box to an element. The class box has a default pink background color defined in its stylesheet which gets overridden by a user defined blue background color.
But please do make this configurable in your jQuery plugin. You want to enable developers to bundle all their css, including your plugins, to optimize resource delivery to the client. Plus injecting stylesheets might be a small performance hit.
It may seem annoying but separating the model, view, and controller is the correct way. You're using jQuery so why not consider how jQuery would approach the situation: a jQuery UI widget like the Accordion comes with several stylesheets, the most important being the base stylesheet and a separate 'theme' stylesheet that (if done correctly) is nondestructive and can be modified without risking the integrity of the widget. You may also want to consider how your favorite plugins are authored and what makes them appeal to you. It's my personal opinion CSS should never be present in JavaScript files however if you've made up your mind, the solution #ckuijjer provided is sound. Hope this helps!

javascript onclick function to enlarge text

I'm not sure why, but I can't seem to get this to work.
Here is my function to enlarge my font.
<script type="text/javascript">
function growText() {
var text = document.getElementById("t_left_text");
text.font-size=22px;
</script>
And here is where I call it
<div id="t_left" onclick="growText()">
<br />
<p id="t_left_text">Mountains are beautiful land structures <br /> that are a result of plate tectonics.</p>
<br />
</div>
Try:
text.style.fontSize = "22px";
DEMO: http://jsfiddle.net/C2MWN/
When you want to change an element's CSS, you need to use the style property. To determine the name of the specific style property, the CSS name is converted to camel case - "font-size" becomes "fontSize", so that the identifier is valid in JavaScript.
While setting the style properties definitely works, and although this is a very simple example, it might be easier to deal with adding and removing a class. This is especially useful when setting multiple CSS properties. The class could be defined as:
.enlarged-font {
font-size: 22px;
}
And you would manipulate the text.className property (and/or the classList property).
Depending on the browser you're using, you could have easily provided a better description (as obvious as it was for some of us) of the problem by using the JavaScript console in the browser. In Firefox, you could use Firebug. In Internet Explorer and Chrome, you could use Developer Tools. If installed/enabled, these can usually be brought up by pressing the F12 on your keyboard.
Also, don't forget to close your function with a }.
Reference:
style property: https://developer.mozilla.org/en-US/docs/DOM/element.style
classList property: https://developer.mozilla.org/en-US/docs/DOM/element.classList
Use below code
function growText() {
var text = document.getElementById("t_left_text");
text.style.fontSize ="22px";
}
Working example http://jsfiddle.net/D2anZ/
Here's a version that uses CSS to accomplish what you want. That way if you want to do this to different sets of text at the same time, and want to change that font size, there's only one place you need to make the change. (Or if you also want to add other css properties (color, etc.)
Fiddle
JavaScript
function growText() {
var text = document.getElementById("t_left_text");
text.className = 'large-font';
}
CSS
.large-font {
font-size: 22px;
}

Javascript: how to change the style of all links in a page?

I'm trying to change the style of all links in a page via Javascript.
I tried both these but no success:
document.links.style.cursor = "wait";
document.getElementsByTagName(a).style.cursor = "wait";
What am I doing wrong?
var allLinks = document.links || document.getElementsByTagName('a');
for(var n=0;n<allLinks ;n++)
document.allLinks [n].style.cursor = "wait";
The document.links is an array of elements, so document.links.style.cursor = "wait" equals to [link1,link2].links.style.cursor = "wait".
And about document.getElementsByTagName(a): the syntax is wrong, you forgot the quotes. The correct is document.getElementsByTagName("a")
var style = document.createElement("style");
document.head.appendChild(style);
try {
style.innerHTML = "a { cursor: wait; }";
}
catch (_ie) {
style.styleSheet.cssText = "a { cursor: wait; }";
}
Of course alternatively you could plan in advance for the eventuality of needing your links to change, and pre-load a static style sheet like this:
.wait-links a { cursor: wait; }
Then whenever you add the class "wait-links" to the <body> (or any container you like), the <a> tags will all be affected. That'd be much more efficient than iterating over the elements changing their individual styles (probably), though if there aren't many links it probably doesn't matter.
Using a style sheet for such things is, in my opinion, a much better practice. In this case, in fact, it'd be better not to call the class "wait-links", but rather use some word or words that describe what's actually happening. Then your JavaScript code just establishes the situation by adding (or removing) the class, and the style sheet controls the appearance changes. If you decide that in some cases the situation calls for the links to change color or become invisible, you can do that without having to root around in your scripts looking for style changes.
Using the JQuery and the ".css" method removes the need to have a for loop and simplifies the code.
$('a').css("cursor","wait");

Categories