Show DIV On Highlight Then Hide - javascript

I'm attempting to have a hidden div tag display when highlighting specific text. I was able to get a hidden div to display on highlighting but the 2 parts I cannot accomplish are:
Only show when highlighting specific text (I assume using a span tag id or something similar)
After the display has been changed to block, change it back to hidden after 5 seconds.
Here is my attempt. Again, this does show the hidden div on highlighting but that's as far as I got. Please help!
function ShowNote() {
document.getElementById('Note').style.display = 'block';
}
document.onmouseup = ShowNote;
if (!document.all) document.captureEvents(Event.MOUSEUP);
function HideNote() {
document.getElementById('Note').style.display = 'hidden';
}
setTimeout("HideNote()", 5000); // after 5 secs
I DON'T want it to show when I highlight this text
<br />I DO want it to show when I highlight this text.
<div type='text' id='Note' style="display:none;">HIDDEN DIV CONTENT</div>

You're very close!
Here's what I have:
function ShowNote() {
if(window.getSelection() == "I DO want it to show when I highlight this text.")
document.getElementById('Note').style.display = 'block';
setTimeout(function(){
document.getElementById('Note').style.display = 'none';
}, 5000); // after 5 secs
}
document.onmouseup = ShowNote;
if (!document.all) document.captureEvents(Event.MOUSEUP);
I DON'T want it to show when I highlight this text<br />
I DO want it to show when I highlight this text.
<div type='text' id='Note' style="display:none;" >HIDDEN DIV CONTENT</div>
Changes:
You need to check what is highlighted via the "window.getSelection()"
function.
You were passing a string to setTimeout
hidden isn't a valid display option, none is
So you know, it's generally bad practice to just have text floating around outside of tags. So it's best to stick your first two lines in <p> tags or something.

You are using quite old and antiquated code. Here's the modern approach:
function showNote() {
document.getElementById('Note').classList.remove("hide");
setTimeout(hideNote, 5000); // after 5 secs
}
function hideNote(){
document.getElementById("Note").classList.add("hide");
}
document.getElementById("select").addEventListener("mouseup", showNote);
.hide { display: none; }
#select { color:red; }
<div>I DON'T want it to show when I highlight this text</div>
<div>I DO want it to show when I highlight <span id="select">this text</span>.</div>
<div type='text' id='Note' class="hide">HIDDEN DIV CONTENT</div>

This is what I did for you.
I setup interval. that occurs every time you mouse out.Or even better it will check if it's your div's style is block on the page.
Hope this helps
Live exapmle on Codepen
var target = document.getElementById('note');
var i = setInterval(function(){
if (document.getElementById("note").style.display == 'block') {
hide();
}
}, 5000);
function showNote() {
target.style.display = 'block';
}
function hide(){
document.getElementById("note").style.display = "none";
}

Related

Javascript - show hidden div if 'checked' is present on a div element (not a checkbox element)

I have something that is likely simple, but I'm struggling :/
I am trying to show a hidden div if the parent element is 'checked' (it is not a checkbox, but we're adding checked to the div if it's clicked on). Here's a screenshot of what the checked looks like in my local environment (screenshot attached).
Here's the code with the div 'checked' and I suspect this should make the hidden div show, but it is not.
Here's the guide I'm following, and the code example below: https://www.w3schools.com/howto/howto_js_display_checkbox_text.asp
var checkBox = document.getElementById("accordionButton");
// Get the output text
var text = document.getElementById("accordionContent");
// If the element is checked, display the accordion content
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
<body>
<div id="accordionButton" checked> <!-- here is where when check is true, I want to show accordion content -->
<p>
<span>Migrate from another platform</span>
</p>
<div id="accordionContent">
option 1 option 2 option 3 option 4
</div>
</div>
</body>
Thank you all for your input. I tried various combinations from your feedback, but they didn't have the effect I was looking for.
Here's what I ultimately ended up with. If there's a better way to write this please let me know. This works in the live environment where the checkbox attribute can be toggled.
I appreciate your help!
document.body.addEventListener('click', function(e){
var button = document.getElementById("accordionButton"); // Get the clickable div
var text = document.getElementById("accordionContent"); // Get the hidden div
// If the checkbox is checked, display the output text
if (button.getAttribute("checked") === null) {
text.style.display = "none";
} else {
text.style.display = "block";
}
});
#accordionContent {
display: none;
}
<div id="accordionButton" checked>
<p>
<span>Migrate from another platform</span>
</p>
<div id="accordionContent">
option 1 option 2 option 3 option 4
</div>
</div>

JavaScript function to replace HTML contents for a few seconds, then revert back.

I'm making a hangman game using JavaScript and need to hide some HTML for a few seconds to display an error message, and then revert back to the original HTML. I've tried using setTimeout(); and setInterval(); but those seem to just wait a few seconds before displaying the error message.
Here's the code for reference:
<div class="row text-center">
<div id="alredGuess" class="col">
<div>
<span id="guessedLetters"></span> <br>
</div>
<div>Guesses left:<span id="guessesLeft">10</span></div>
<div>Wins:<span id="wins">0</span></div>
<div>Losses:<span id="losses">0</span></div>
</div>
</div>
JS:
if (gameRunning === true && guessedLetterBank.indexOf(letter) === -1) {
// run game logic
guessedLetterBank.push(letter);
// Check if letter is in picked word
for (var i = 0; i < pickedWord.length; i++) {
//convert to lower case
if (pickedWord[i].toLowerCase() === letter.toLowerCase()) {
//if match, swap placeholder
pickedWordPlaceholderArr[i] = pickedWord[i];
}
}
$placeholders.textContent = pickedWordPlaceholderArr.join("");
checkIncorrect(letter);
} else if (gameRunning === false) {
$placeholders.textContent = "Press \"A\" To Begin!"
} else {
//alert("You've already guessed this letter.")
function newAlert() {
var hideDiv = document.getElementById("alredGuess");
if (hideDiv.style.display = "block") {
hideDiv.style.display = "none";
}
}
hideDiv.textContent("You've already guessed this letter!");
function showDiv() {
var showDiv = document.getElementById("alredGuess");
if (hideDiv.style.display = "none") {
hideDiv.style.display = "block";
}
}
}
}
setInterval(newAlert, 3000);
}
Tip 1
Well, first of all i don't recommend using display: block|none to show or hide DOM elements. Instead try using visibility: visible|hidden or better, toggle a css class name such as : .hidden. That's because when you set a DOM element's display to none, its width and height are gonna be set to zero, often causing an unwanted loss of space because the DOM node visually collapses. With the visibility property, for example, the element just disappears without loss of space.
Tip 2
Error/status messages should always live within their own containers. Do not display messages in substitution of some content you need to revert back after.
It is always better to prepare an empty <div>, hide it by default with a generic .hiddenCSS class and then remove this one as soon as you need to display the container.
Suggested solution
Now, in your case, i think you're using setIntervalin the wrong way. You have to immediately show the alert message, then make it disappear after a few seconds.
As suggested above, this should be done by toggling CSS classes, using different containers and using setTimeout in order to remove/add the CSS classes as soon as the interval is over. Basically, the setTimeout restores everything to its original state.
So, given this HTML code:
<div id="alredGuess">This is the original text</div>
<div id="alertbox" class="hidden"></div>
and this CSS code:
.hidden { visibility: hidden; }
try this:
var alertTimeout = 1000; // Timeout in milliseconds.
function showAlertMessage() {
// This is your original text container.
var alredGuess = document.getElementById("alredGuess");
// This is the new error message container named #alertbox
var alertBox = document.getElementById("alertbox");
// Now let's fill it with the specific error text (better using HTML here).
alertBox.innerHTML = "You've already guessed this letter!";
// Hide the original container by adding an .hidden css class.
alredGuess.classList.add('hidden');
// Show the error message container by removing its default .hidden css class.
alertBox.classList.remove('hidden');
// Then set up an interval: as it ends, revert everything to its original state.
setTimeout(function() {
alertBox.classList.add('hidden');
alredGuess.classList.remove('hidden');
}, alertTimeout);
}
// Call the function.
showAlertMessage();
Fiddle: https://jsfiddle.net/qyk4jspd/
Hope this helps.

How can I hide some elements when showing another?

I'm finishing my website and I have a script which is hiding or showing a div when a button is pressed.
Here is code :
function display(id) {
var e = document.getElementById(id);
if (e.style.display === "none") {
e.style.display = "block";
} else {
e.style.display = "none";
}
}
But this code is not truly what I'd like because I only want that one div can be displayed at the same time (ex : if div 4 is active and the user need to see the div 2, it has to hide the first one). I have just used JS for quick things therefore I don't have any idea how to do this.
Also would it be possible to hide a specific div depending from which link the user comes on the page.
Exemple of my html :
<a onclick="display('1_1_1')">button</a>
<div id="1_1_1" class="well" style="display: none;">
<h1>Title</h1>
</div>
Thank you for your help !
It is better to add a class which contains display: none like
.no-display {
display: none;
}
then just add or remove that class when you click on a div like
parentDiv.addEventListener("click", function() {
const elem = getElemenyById("elemID");
if(something) {
elem.classList.add("no-display");
else if(something) {
elem.classList.remove("no-display");
};
});
You can create a class with display property and you can add it using Jquery.
CSS:
.display_none_class {
display: none;
}
Jquery:
<script>
$( "#element_ID" ).addClass( "display_none_class" );
</script>
But this sometimes has aligning issues. So, you can use CSS as:
.display_none_class {
width:0;
visibility: none;
}
You can implement this by toggle class:
$("#button_ID").click(function(){
$("#element1_id").toggleClass("display_none_class");
$("#element2_id").toggleClass("display_none_class");
});
First, add this class to the element which you want to hide first. Then On clicking button, it will toggle the class and will make one element visible and other hide.
First add this

JS expand onClick multiple events

Please check this page first : Solarking - About Us
Check first 2 boxes which has a READ MORE button. On clicking them, they expand a paragraph.
Now I want it to be like when I click on it, it should expand the text and change the button value to "CLOSE" from "READ MORE". And on again clicking on "CLOSE", it should change value to "READ MORE".
I searched for long time to see how to fire multiple events on onClick, but I saw that some said to use a ; in them, some said make a new function and put 2 functions in it.
Now I tried to make a new function with 2 functions inside it (one to expand the paragraph, other to change value of button, but I failed. (I am new to JS).
Help please. Thank you in advance!
Code I have on the page :
button code:
<p style="text-align: right;"><input id="button12" style="background-color: #eca200; color: #ffffff;" onclick="return toggleMe('para1')" type="button" value="Read more" /></p>
Script :
<script type="text/javascript">
function toggleMe(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block"
}
else{
e.style.display="none"
}
return true;
}
</script>
I think the easiest way to do this would be to set a boolean variable. In other words, let's say that it starts off with the dclaration at the beginning of the page.
var hasbeenclicked = false;
Then, after the first click
hasbeenclicked = true;
After a second click
hasbeenclicked = false;
When the function is called, it checks the variable and operates accordingly. The following is not real JS....
if hasbeenclicked = true {
do some stuff;
}
else {
do some other stuff;
}
That is a simple way to accomplish what you are trying to do.
Additional info:
Use two DIV tags with separate ID's. One for the paragraph and one for the "label". Use getelementbyID to alter each one appropriately.
I noticed you are using jQuery.
You could use a toggle method.
Alter the html link. Add a class of expander and use the data attribute to identify the paragraph id
<p style="text-align: right;">
<input id="button12" data-toggle="para1" class="expander" style="background-color: #eca200; color: #ffffff;" type="button" value="Read more" />
</p>
The JS
$(".expander").click(function() {
var self = $(this);
$("#" + self.data('toggle')).slideToggle(500, function () {
if ($("#" + self.data('toggle')).is(':visible')) { // paragraph is open
self.val("Close");
} else { // paragraph is closed
self.val("Read More");
}
});
});

Javascript if else statement to hide and show div

Please refer to the following codes :
<div id="message-1" onclick="javascript:showresponddiv(this.id)>
</div>
<div id="respond-1" style="display:none;">
</div>
<div id="message-2" onclick="javascript:showresponddiv(this.id)>
</div>
<div id="respond-2" style="display:none;">
</div>
<script type="text/javascript">
function showresponddiv(messagedivid){
var responddivid = messagedivid.replace("message-", "respond-");
if (document.getElementById(responddivid).style.display=="none"){
document.getElementById(responddivid).style.display="inline";
} else {
document.getElementById(responddivid).style.display="none";
}
}
</script>
The codes above already success make the respond div appear when user click on message div. The respond div will disappear when user click on message div again. Now my question is how to make the respond div of 1st message disappear when user click on 2nd message to display the respond div of 2nd message?
You should give the "respond" divs a common class:
<div id="respond-1" class="response' style="display:none;"></div>
Then you can get all divs by using getElementsByTagName, compare the class and hide them on a match:
function hideAllResponses() {
var divs = document.getElementsByTagName('div');
for(var i = divs.length; i-- ;) {
var div = divs[i];
if(div.className === 'response') {
div.style.display = 'none';
}
}
}
We cannot use getElementsByClassName, because this method is not supported by IE8 and below. But of course this method can be extended to make use of it if it is supported (same for querySelectorAll). This is left as an exercise for the reader.
Further notes:
Adding javascript: to the click handler is syntactically not wrong but totally unnecessary. Just do:
onclick="showresponddiv(this.id)"
If you have to do a lot of DOM manipulation of this kind, you should have a look at a library such as jQuery which greatly simplify such tasks.
Update: If always only one response is shown and you are worried about speed, then store a reference to opened one:
var current = null;
function showresponddiv(messagedivid){
var id = messagedivid.replace("message-", "respond-"),
div = document.getElementById(id);
// hide previous one
if(current && current !== div) {
current.style.display = 'none';
}
if (div.style.display=="none"){
div.style.display="inline";
current = div;
}
else {
div.style.display="none";
}
}
Edit: Fixed logic. See a DEMO.
You can add some class to all divs with id="respond-"
e.g
<div id="respond-1" class="classname" style="display:none;"></div>
<div id="respond-2" class="classname" style="display:none;"></div>
Now at first row of your function "showresponddiv()" you should find all divs with class "classname" and hide them.
With jQuery it is simple code:
$(".classname").hide();
jQuery - is a Javascript Library that helps you to easy manipulate with DOM and provides cross-browser compatibility.
Also you can look to Sizzle - it is a JavaScript CSS selector engine used by jQuery for selecting DOM elements

Categories