Javascript hide element(s) and put something else in place - javascript

I have a small question.
For a task we have to make in Javascript I need some help.
We have a text and some words we give an id (html). In javascript we have to make a function that when it's clicked, all the words with the id become invisible. I know, I can do this too. But there's one more thing. If we put the word invisible, it has to become clear there was a word there before! It would look like a fill-in text, if you can understand.
Now I have this:
function toggle_woordjes() {
var e = document.getElementsByClassName('invul');
for(i = 0; i < e.length; i++){
if (e[i].style.display !== ''){
e[i].style.display = '';
}
else {
e[i].style.display = 'block';
}
}
}
The code doesn't work properly anymore because I changed it so much that I can't get back to the original.
I hope you people can help me.
Sorry that my English isn't the best!
Cheers

If the parent's background is only 1 color (no design nor pattern), you may write something like the following.
object.style.backgroundColor="same color as parent"
however if the background is more complex:
function toggle_words() {
var doms = document.getElementsByClassName('class_name');
for (var i = 0; i < doms.length; ++i) {
var domStyle = doms[i].style;
if (domStyle.visibility === 'visible') {
domStyle.visibility = 'hidden';
}
else {
domStyle.visibility = 'visible';
}
}
}
I use visibility instead of display because the elements stay in the DOM, thus the user knows there was something before.

For one thing, I think that you need to make it e[i].style.display = 'none'; rather than empty string in order to make them disappear (and change the test accordingly).
But it sounds like that wasn't your real problem but rather displaying text to indicate that there was an element there. I would suggest having a <div> with class 'invul' that contains 2 other <div> elements: 1 is the text to display if the real content is invisible and the other is the real content. Something like this:
<div class="invul">
<div class="msg">Word was here</div>
<div class="word">I am the real message</div>
</div>
Then make them disappear and reappear as needed.

Related

How do I insert text here in Javascript

I have javascript that will open this window, but I need after opening this chat to insert text there and send it. Also would appreciated if you could help me improve my code.
setInterval(function acceptor() {
var btn = document.getElementsByClassName('button green');
for (var i = 0; i < btn.length; i++) {
if (btn[i].innerText.indexOf('Accept') > -1) {
btn[i].click();
console.log('Accepted in to IMs');
}
}
}, 1000);
console.log('Acceptor started');
setInterval(function getnick() {
var cnt = document.getElementsByClassName('notificationsSlider');
for (var j = 0; j < cnt.length; j++) {
if (cnt[j].innerText.indexOf('is now your contact') > -1) {
var nickname = cnt[j].innerText;
var onlynickname = nickname.split(' is now your contact').shift();
console.log(onlynickname);
var contactlist = document.getElementsByClassName('userName');
for (var k = 0; k < contactlist.length; k++) {
if (contactlist[k].innerText.indexOf(onlynickname) > -1) {
contactlist[k].click();
console.log('Opened chat');
}
}
}
}
}, 3500);
console.log('Openner started');
EDIT:
I just found out that it won't be that easy I guess. At first point: I am trying to make JS to accept contact request, open chat wih it and post/send auto message to the accepted contact.
Today I found out that that "text box" - thing where I need to insert my custom auto message text is changing dynamically.
When my code that so far opens the chat with the contact it looks like this. <br data-text="true">
After I insert there some text by myself it changes to this: <span data-text="true">I inserted text here</span>
Could anyone help me out how to write js that will after oppening chat also insert my custome message there?
The question asks how to insert text into a particular span element. Inserting text into an element can be done by the e.g. el.innerHTML='The text';
To do that you first have to find the element. Looking at the screenshot provided it seems as though the span element needed is the only one with a data-text="true". We therefore need to find that.
You ask for suggestions to improve your code. If this bit is your code and you are able to add things to your HTML I would suggest you think about giving elements which are unique and which you want to use unique identifiers. For example:
<span id="datatext"></span>
JavaScript can then find it quite simply:
el=document.getElementById('datatext');
If you aren't in a position to do that then the only way I can think of is to look at all the span elements in the document and find those which have data-text="true"
Here is an example of doing that on a document with a few spans - just one of which has that attribute. (thanks to #Adriani6 for the querySelectorAll information)
<span data-text='false']></span>
<span data-text='true']></span>
<span data-somethingelse='true']></span>
<span data-number='3']></span>
<script>
var spans = document.querySelectorAll("[data-text='true']");
if (spans.length==1) {
console.log('Success I have found the span element required.');
spans[0].innerHTML='The text you want to put in';
}
else {
console.log('Help, there are '+ spans.length + ' span elements with data-text="true" so I do not know where to put the text');
}
</script>
It isn't really possible to be of great help with your Javascript code as there isn't enough information to know exactly what it is trying to do. One thing I noted was that you are simulating clicks (rather than waiting for the user to click) the green buttons and I wonder if that is what you intended - and if it is why you need a seconds pause before doing so? [the OP has clarified that].

How to capture specific the character that was clicked on inside of a contenteditable div

I'm looking for a way to capture the specific character (or character index in text) after the user clicks on it inside of a contenteditable div. Just to provide an example, please consider the following HTML:
<div contenteditable="true">
Hello world
</div>
Suppose the user clicks right between "o" and "r", is there a way to know that, using JavaScript?
I'd imagine this would be covered by the Selection API but all my inquiry so far has produced me nothing.
I appreciate any help that you can give me.
You can see the caret position, i have done a small snippet for you here. Have a look at it.
enter code herehttp://codepen.io/19sthil80/pen/pEooVR
You can always do something like this. Codepen Link
I have put an alert in so that you can see that it does indeed know what you clicked and if you click a space as in between Hello and World it knows as well.
var div = document.getElementById("div");
function clickify (e) {
var arr = (typeof e.innerText !== 'undefined') ? e.innerText.split("") : e.textContent.split(""),
max = arr.length,
i = 0,
template = "$c",
result = "";
for (; i < max; i += 1) {
result += template.replace("$c", arr[i]);
}
e.innerHTML = result;
}
clickify(div);

javascript collapsible table without jquery

This is a simple question I can't seem to figure out and every google search returns a million ways to do this via jquery, but I'd prefer to use vanilla javascript because I am new to it and want to learn it well before using any libraries. What I am trying to do is have a button collapse part of a table when clicked and then show those hidden parts again when clicked again. Basically just toggling the display of a class of elements.
I have a button that calls the test() function
when clicked nothing on my table changes. Here is my javascript code. I am using collapse[0] because if I understand it correctly collapse is a nodeList and I always close and open all of these together so I only need to check the first element.
function test() {
var collapse = document.getElementsByClassName("catOne");
var i = 0;//Counter for loops
if(collapse[0].style.display === "table-row"){
for(i = 0; i < collapse.length; i += 1){
collapse[i].style.display = "none";
}
}
if(collapse[0].style.display === "none"){
for(i = 0; i < collapse.length; i += 1){
collapse[i].style.display = "table-row";
}
}
}
I've tested the function with this code:
function test() {
var collapse = document.getElementsByClassName("catOne");
var i = 0;//Counter for loops
for (i = 0; i < collapse.length; i += 1) {
collapse[i].style.display = "none";
}
which works fine on collapsing the elements so evidentally the issue is with my if statement, but my IDE, Netbeans, doesn't throw any errors and as far as I can tell it should be working.
Thanks for the help.
Link to html and javascript: https://jsfiddle.net/ozjbekjy/
I suspect there are a few problems working against you.
First, you need to make sure the test() function is defined earlier in the page than it's being used. With jQuery, that means using the $(function(){}) wrapper to apply event handlers on DOM ready. You can approximate the same thing yourself with something like this answer.
Otherwise, simply place the <script> tag somewhere before the table (probably in the <head>), and the onclick will work.
You also are using i += 1 where you could be using i++ - they accomplish the same behavior.
Secondly, instead of manipulating the style attribute, use the classList.toggle() function to simply add and remove a class that has the rule display: none, like so:
CSS
.hide-me {
display: none;
}
JavaScript
function test() {
var collapse = document.getElementsByClassName("catOne");
for (var i = 0; i < collapse.length; i++) {
collapse[i].classList.toggle("hide-me");
}
}
Your JSFiddle, with the suggested updates: https://jsfiddle.net/ozjbekjy/4/

How do I display a single new word of a paragraph at a time, moving by keypress or mouseclick?

Say I have something like this:
<p>Here are several words in a sentence.</p>
I'm trying to figure out how to display each word, one by one, via keypress or mouseclick, till it reaches the end.
So for example:
Here (click)
Here are (click)
Here are several , etc.
This may be basic, but I'm not very good and I'd love some help!
Thanks!
I just want to make some interventions on #Dean.DePue answer and make the code so you paste it in your project and does the trick:
Your html should look like this:
<div id="adiv"></div>
And you should add this javascript code too:
var index, newsentence, sentence, words;
sentence = "Here are several words in a sentence";
words = sentence.split(" ");
index = 0;
newsentence = "";
$(document).click(function(e) {
if (e.button === 0 && index < words.length) {
newsentence += words[index];
newsentence += " ";
$("#adiv").html(newsentence);
index = index + 1;
}
});
If you've got any doubt of the code just ask!
This has been turned into a jQuery Plugin: word-reveal.
While the other two answers will work (sort of), they aren't very reusable. What happens when you have more than one container you'd like to reveal with more than one sentence? I created a jQuery plugin that can easily be reused throughout the page.
The Setup
Include jQuery on the page
Download the plugin from GitHub, and include it on the page
You're set and ready to go!
The HTML
Set an id for each div or p tag. An example of multiple uses:
<p id="firstRevealer"></p>
<p id="secondRevealer"></p>
<p id="thirdRevealer"></p>
The jQuery
$(document).ready(function() {
$("#firstRevealer").wordReveal({text:"This reveals one word at a time."});
$("#secondRevealer").wordReveal({text:"Adding more text is easy!"});
$("#thirdRevealer").wordReveal({text:"It <b>also</b> works on <em>some</em> tags, since it splits on <b>spaces</b>!"});
});
The CSS
I added CSS on the example, to make clear where you're clicking to reveal the next word. A different answer registered clicks on the document, but any clicks (for a expandable menu, for example) would add a word.
p {
padding: 10px;
margin:10px;
min-height:25px;
background-color:#BADA55
}
The fiddle.
Note
This can easily be extended to act on other events (keypress).
<script type="text/javascript">
var sentence = "Here are several words in a sentence";
var words = sentence.split(" ");
var index = 0;
var newsentence = "";
function clickit() {
newsentence += sentence[index];
index = index + 1;
}

Only one function rather than many that are looking the same?

Bonjour ! here is my question, I'm using, two "kinds" of JS short functions (5 lines of code per function) but I have to make, let's say, about 10 of each kind. It would be a total of 100 lines of code which is very long... So I was wondering if there could be an easy and very shorter way to implement this. I know very very few in javascript and I like roughly understand what I write. (If possible, avoid using JQ, for which I absolutely don't understand a word !)
Here are the functions :
function typedepolice() {
var nodes = document.getElementById('stripid').childNodes;
var nompolice = document.Selections.police.options[document.Selections.police.selectedIndex].value;
for(var i=0; i<nodes.length; i++) {
if (nodes[i].nodeName.toLowerCase() == 'div') {
nodes[i].style.fontFamily = document.Selections.police.options[document.Selections.police.selectedIndex].value;
}
}
}
html calling : ...<select name="police" id="police" size="1" onchange="typedepolice()">...
function colbandeau() {
var nodes = document.getElementById('stripid').childNodes;
var colorFmsg = document.getElementById("colorFmsg").value;
for(var i=0; i<nodes.length; i++) {
if (nodes[i].nodeName.toLowerCase() == 'div') {
nodes[i].style.background = '#' + document.getElementById("colorFmsg").value;
}
}
}
html calling : ...<input id="colorFmsg" class="color3" value="FFFFFF" size="5" onchange="colbandeau()">...
The first one refers to a selected option of a dropdown selection box.
The second one to a color selected with JSColor which is a JS plugin to choose a color.
As you see, they are intended to dynamically change CSS properties of numerous div children of one element which Id is "stripid", and are called by "onchange" events.
After a long search, I found the pattern of these functions in a reply in stackoverflow and they are exactly what I needed. For this, I thank very largely Vijay Agrawal, because it will improve a lot my web page.
NB : don't be afraid, "police" is meaning "font" in French :)
If someone could help me, it would be great !
You can create a function to set the stripid child nodes
function setNodeStyle(value, style) {
var nodes = document.getElementById('stripid').childNodes;
for (var i=0; i<nodes.length; i++) {
if (nodes[i].nodeName.toLowerCase() == 'div') {
nodes[i].style[style] = value;
}
}
}
Then you can call it in the other functions:
function colbandeau() {
setNodeStyle(document.getElementById("colorFmsg").value, "background");
}
This will already save you quite a bit.
You can improve on this even more by setting an attribute that contains the value that is to be. To get you started:
<input class="color3 changer" value="FFFFFF" size="5" data-style="background">
Array.prototype.forEach.call(document.querySelector(".changer"), function (el) {
el.addEventListener("change", function () {
setNodeStyles(this.value, this.dataset.style);
});
});

Categories