How to apply css rule to a Javascript expression? - javascript

$("#confirm_text").text("Are you sure you want " +this.name +" "+ this.type +"?");
The whole phrase is white, but I want to make this.name and this.type orange. JS method fontcolor doesn't work. Any way to do this?

Try this :
"Are you sure you want <span style='color: orange'>" +this.name +" "+ this.type +"</span> ?"
Here you can see demo : http://jsfiddle.net/2pRzX/

this may work.
"Are you sure you want " +<span class="orange">this.name</span> +" "+ <span class="orange">this.type</span> +"?"
and apply css:
.orange{
color:orange;
}

I usually use < span class="orange"> this.name < /span> for this case.
In css .orange{color:orange;}

You have to put the text in some kind of HTML element, like <span>. Either you do it with innerHTML, which is the simpler method, or by creating the elements one by one.
Using jQuery (updated answer)
As the question was updated, I updated my answer to fit the new question.
Instead of .text, you can use the .html method which works like element.innerHTML = (see below in the old answer). It parses HTML code and inserts it into the element. Note that you should enclose the string in single quotes so that you can use double quotes without escaping them.
$("#confirm_text").html('Are you sure you want <span style="color:orange">' + this.name + ' ' + this.type + '?');
Using plain JavaScript (old answer)
This answer is outdated because the question has changed and jQuery rather than plain JS is required. I leave this here for later reference.
innerHTML
When you add HTML code to an existing element in the DOM, the browser will parse the string and create new elements. You can include the <span> tag in the string and the browser will create an element.
var targetDIV = document.getElementById("targetDIV");
// Add the text with innerHTML
targetDIV.innerHTML = 'Are you sure you want <span style="color:orange;">' + this.name + ' ' + this.type + '</span>?';
Creating the elements
Sometimes you can't just use innerHTML, especially if there is already text in the target element. This is an alternative:
var targetDIV = document.getElementById("targetDIV");
// Append the first peace of text
targetDIV.appendChild(document.createTextNode("Are you sure you want "));
// Create the span element
var orange = document.createElement("span");
// Change its text-color
orange.style.color = "orange";
// Add the text to the span
orange.appendChild(document.createTextNode(this.name + " " + this.type));
// Append the span to the target element
targetDIV.appendChild(orange);
// Append the question mark
targetDIV.appendChild("?");
Which to use?
In most cases, you can use either of these methods. I always use the second one, though, because I have the feeling that it is the "cleaner" one. You have more control over what happens, you can change things by adding/removing/changing lines instead of modifying a large string. You also don't have to check whether your HTML is valid. But as I said, both methods work.

Try this:
"Are you sure you want <span style='color: orange'>" +this.name +" "+ this.type +"</span>?"

You can add <span> </span> tags around the name and type values, and add an colour using CSS.
Example:
http://jsfiddle.net/BAhUG/

Related

What's the best way to append html tags to existing text?

I want to use the currently selected text in the office document to be replaced by the same selected text but surrounded with html. Effectively adding a hyperlink to the current selection.
I first read the text property of the selection
var objRange = objContext.document.getSelection();
objRange.load('text');
followed by
return objContext.sync().then(function(){
var strSelection = objRange.text;
objRange.insertHtml(
"<a href='" + decodeURIComponent(strHyperlink) + "'>" + strSelection + "</a>",
Word.InsertLocation.replace
);
return objContext.sync().then(function(){
objDialog.close();
});
});
I need a sync to read the text and then another one to write the updated text back into the document after that I close a dialog. But this sometimes causes the html to get written into the document twice. Is there a better way of doing this instead of with double context syncs?
To answer your question, if you need to read the text and then write into a different context, you'll need two syncs.
But you might take a look at the Range.hyperlink property, which is writeable. I don't know if it'll give you a way to avoid two syncs, but is intended for what you seem to be using insertHtml to do.

How do I make Drive API WebViewLink URL clickable?

appendPre(file.name + ' (' + file.viewedByMeTime + ')'+ ' (' + file.webViewLink + ')' +' (' + file.quotaBytesUsed + ' bytes)');
When it displays: Its shows this
How can I make the URL clickable?
Also, how can I bold file.name and change the color of the text?
Edit
#Pig correctly pointed out that you are allowed to put content into a <pre> tag, it's just a real pain for no real benefit. If your goal is to make a list of items with clickable links, I think a <ul> and adding <li>'s with Javascript is better. Maybe even a <table> and adding rows! Delicious.
What's up #Pig! It's your bro #jdbiochem. Here's the appendPre() function I think you're talking about (you should post the functions you're using in a question like this :) ).
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
This adds to a <pre> tag, which renders preformatted text. You can't shouldn't really put anything in a <pre> tag besides text itself. So, you might think about making a different function to make a link, maybe something like this:
function appendLink(url) {
// create a DOM node, an <a> tag.
var link = document.createElement('a');
// a "text node" is what lives inside the tag <a>text node</a>
var _text = document.createTextNode("click me");
// add that text node to the link, so now we have: <a> click me </a>
link.appendChild(_text);
// set the actual link in the href attribute
link.href = url;
// add a CSS class so we can control the style of text easily
link.classList.add('drive-link');
// add this link somewhere in your document
doucment.getElementById('links').appendChild(link);
}
Keep in mind this function takes only the URL, so using it in all the places you have appendPre() will not work.
If you want the link bold and a different color, your CSS class might look like:
.drive-link {font-weight: bold; color: peachpuff;}
(BTW, you should mark answer to your earlier question correct!)

HTML Label name instead of ID?

I am making website where I am created a lot of labels that are assigned in output as here
Use fiddle link at the end of the post
<!-- lets say that I want to make a kind of board to show some game clans or... whatever -->
<label class='team' name='ally'>Madcowz</label><BR>
<label class='team' name='ally'>Fluffy Unicorns</label><BR>
<label class='team' name='enemy'>Blue bastards</label><BR><BR>
<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>
<!-- The problem is that the NAME tag does not exist for label in this case: -->
<!-- I can't use ID because ID should be unique values -->
<script>
var teams = $(".team");
for(i=0; i<teams.length; i++)
{
document.getElementById('printSomeOutputHere').innerHTML += teams[i].name + ": " + teams[i].textContent;
document.getElementById('printSomeOutputHere').innerHTML += "<BR>";
}
</script>
Fiddle:
http://jsfiddle.net/cusnj74g/
name attribute is undefined, so how can I mark these labels with same name if I can't use (I can, but I should not) ID
A couple of points:
You seem to know that name is not a valid attribute for label elements. So don't use it, use data-name instead.
You're using label elements incorrectly. There are two ways you use label: A) By putting the input, select, or textarea it relates to inside it (<label><input type="checkbox"> No spam please</label>), or by using the for attribute to associate it with one of those elements elsewhere in the document (<label for="no-spam-please">No spam please</label>...<input id="no-spam-please" type="checkbox">). Having a label with no control in it and no for is fairly pointless; just use a span.
You're using jQuery in one place, but not in others. I suggest that if you're going to have a library on your page, it's best to get full use out of it. In this case, to access the attribute, you'd use $(teams[i]).attr("name") or better, $(teams[i]).attr("data-name") if you're using a data-* attribute (see #1 above). (Some may tell you to use .data to access the attribute; don't, that's not what it's for. But you might consider looking at what it's for and whether that helps you.)
.innerHTML += "content" is an anti-pattern. It makes the browser loop through all elements within the element you're doing it to to build a string, then append the string on the right with it, then parse the result, and delete all existing elements within the element and replace them with the parsed result. Instead, consider .insertAdjacentHTML("beforeend", "content")
You don't declare i anywhere, which means your code falls prey to The Horror of Implicit Globals. Declare i, or use any of several other ways to loop that don't require an index counter.
Your output will be fairly hard to read, recommend breaking it up (perhaps a div for each team?).
textContent is not reliable cross-browser, some browsers use innerText instead. (And there are differences in how whitespace is treated between them.) Since you're using jQuery, use text.
...but yes, the code would work if you used .getAttribute("name") rather than .name. Browsers make access to even invalid attributes available through getAttribute. They just don't necessarily create reflected properties for them.
Here's a version with the various comments above applied:
var output = $("#printSomeOutputHere");
$(".team").each(function() {
var $this = $(this);
output.append("<div>" + $this.attr("data-name") + ": " + $this.text() + "</div>");
});
<span class='team' data-name='ally'>Madcowz</span><BR>
<span class='team' data-name='ally'>Fluffy Unicorns</span><BR>
<span class='team' data-name='enemy'>Blue bastards</span><BR><BR>
<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
...or to avoid repeated appends we could use map and join:
$("#printSomeOutputHere").append(
$(".team").map(function() {
var $this = $(this);
return "<div>" + $this.attr("data-name") + ": " + $this.text() + "</div>";
}).get().join("")
);
<span class='team' data-name='ally'>Madcowz</span><BR>
<span class='team' data-name='ally'>Fluffy Unicorns</span><BR>
<span class='team' data-name='enemy'>Blue bastards</span><BR><BR>
<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
From https://developer.mozilla.org/en-US/docs/Web/API/Element.name:
[The name property] only applies to the following elements: <a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, <map>, <meta>, <object>, <param>, <select>, and <textarea>.
Since you're using jQuery I would use something like:
for(var t in teams){
$('#printSomeOutputHere').get(0).innerHTML +=
teams[t].getAttribute("name")
+ ": "
+ teams[t].text()
+ "<BR />";
}
Use getAttribute instead:
teams[i].getAttribute('name')
Why not use multiple classes:
<label class='team ally'>Madcowz</label><BR>
<label class='team ally'>Fluffy Unicorns</label><BR>
<label class='team enemy'>Blue bastards</label><BR><BR>
And the JS:
<script>
var outEl = document.getElementById('printSomeOutputHere');
var teams = $(".team");
for(i=0; i<teams.length; i++)
{
outEl.innerHTML +=
(teams[i].hasClass('ally')? 'ally':'enemy') + ": " +
teams[i].textContent;
}
</script>

The right way to add to a div?

I am using .text() to add to a div. I don't know how much I will be adding. But if I use .text() more then once it will just add the last one. I have used .text(msg1,msg2,msg3) and this does work for me, but i would like it if the text was more ordered. like after every msg a new line would start. I have tried to add spaces but that does not work and is not the way i want it. I just had a div, i tried adding, <p>'s to it, i tried $("p:first") tried by ID. I have included a fiddle.
http://jsfiddle.net/G24aQ/12/
if(k1<10){
msg1= "This will not space like a want." + " "
msg2= "I don know why not. "
msg3= "How come. "
$('#output1').text(msg1);
$('#p').text(msg2);
$('#output1').text(msg3+" "+msg2+" "+ msg1);
}
You can you use <br/> to add the messages in new lines.
You can use html instead of text and add it all at once. To add one by one, use html and append together.
Demo : http://jsfiddle.net/G24aQ/14/
if (k1 < 10) {
msg1 = "This will not space like a want.<br/>";
msg2 = "I don know why not.<br/>";
msg3 = "How come.<br/>";
$('#output1').html(msg3 + msg2 + msg1); //this will add all the three variables together into #output1 - replacing older content
/*
//To add one by one
$("#output1").html(msg3); // this will erase the older content so that you have a clean #output1 div
$("#output1").append(msg2); //this will add to the existing content, will not over write it
$("#output1").append(msg1); //this will add to the existing content, will not over write it
*/
}
Always keep in mind that html() & text() will erase everything in the selector and add the new content into it. append adds to the existing content. And, your HTML tags will be ignored if text() is used.
Docs for html & append for extra info.
You need to use $(id).append (code); if you want to append, not to change.
As far as i remember, html will only render excessive spaces as one.
You have to use
or put each text inside a span tag with a right margin
<span style="margin-right:10px"></span>
You should use append for that, like:
if (k1 < 10) {
msg1 = "This will not space like a want.<br/>";
msg2 = "I don know why not.<br/>";
msg3 = "How come.<br/>";
$('#output1').append('<p>'+msg1+'</p>'+'<p>'+msg2+'</p>'+'<p>'+msg3+'</p>');
}
and use a html tag like <p> to make them appear in new lines.
You can also do it this way:
if (k1 < 10) {
msg1 = "This will not space like a want.<br/>";
msg2 = "I don know why not.<br/>";
msg3 = "How come.<br/>";
var e = $('<p>'+msg1+'</p>'+'<p>'+msg2+'</p>'+'<p>'+msg3+'</p>');
$('#output1').append(e);
}

How can I get the text that was clicked on in Javascript?

Does anyone know if it is possible with javascript to to tell the position of a mouse click in some text? I know it's easy to get the x,y coordinates, but I'm wanting the position in the text.
For example if I clicked inside <p>foo bar</p>
I want to be able to tell that the click was on/after the 5th character. Or that foo b is before the click and ar is after it.
By the way, I'm using jQuery too, I'm happy with pure JS and solutions that use jQ.
Thanks in advance.
Javascript and browsers don't support this directly, but you could technically wrap each character in a span and do it based on which span was clicked on:
<p>
<span>f</span>
<span>o</span>
<span>o</span>
<span> </span>
<span>b</span>
<span>a</span>
<span>r</span>
</p>
If anybody actually tries this, be prepared to be eaten by a velociraptor :p
Expanding on codeka's answer and my comment . . . try this (i'm assuming your target p has id my_p):
(function() {
var p = $('#my_p');
var o_string = p.text();
p.html('<span>' + o_string.split('').join('</span><span>') + '</span>');
$('span', p).each(function(i) {
$(this).data('MyIndex', i);
}).click(function() {
var char_index = $(this).data('MyIndex');
if (char_index >= 5) {
alert('You clicked after character 5! Before: "' + o_string.substring(0, char_index) + '", After (inclusive): "' + o_string.substring(char_index) + '"');
}
});
})();
What that does is:
1. Find the paragraph where you need per-character clicking knowledge, 2. Split the text in that paragraph into a number of one-character spans, 3. Inform each of those one-character spans of its position in the string, and 4. Assign a click() handler to each span, which spits out the information about the span (including your example of char index >= 5, and printing the before and after parts of the string).
Of course you might want to put that in $(document).ready(...) instead of an anonymous function; I didn't know if maybe you had a precondition for activating this detection though.
Frankly I don't like very much idea of travesting text and 'span'ing it. But I'm not quite sure what you are looking for, if you need just the word clicked and do dblclick instead of click will do, i have next code:
$('*').dblclick(function(event){
console.log((window.getSelection() || document.getSelection() || document.selection.createRange().text).toString());
event.stopPropagation();
});
after that you can deselect text if you want.
Without toString() you will get object that has a lot of properties, study it as well.

Categories