Toggle display of an an element when you click on another element - javascript

I have a p element and a hidden pre element. I want to make it so that when you click on a p element with (for example) id/class = "p1", it changes the display of the pre element with (for example) id/class = "pre1".
This is my javascript code :
var p = 1;
setInterval(function() {
if(p <= document.querySelectorAll(".show").length) {
document.getElementById("display-pre"+p).onclick = function() {
console.log(p);
if(document.getElementById("display-pre-a"+p).style.display == '') {
document.getElementById("display-pre-a"+p).style.display = 'block';
} else if(document.getElementById("display-pre-a"+p).style.display == 'block') {
document.getElementById("display-pre-a"+p).style.display = 'none';
}
};
p++;
if(p > document.querySelectorAll(".show").length) {p = 1;}
}
}, 100);
This code kind of works but not really. It sometimes changes other elements and sometimes does nothing.
This is my full javascript code : https://pastebin.com/wEwdKKLy
This is my html :
<div id="test-div">
<input type="text" id="search"/>
<button type="submit" onclick="query()">Submit</button>
<button type="submit" onclick="newInput()">New</button>
<button type="submit" onclick="remove()">Delete</button>
<button type="submit" onclick="deleteAll()">Delete All</button>
<div class="query-div"><p class="query-p">Test-a</p></div>
<div class="query-div"><p class="query-p">Test-b</p></div>
<div class="query-div"><p class="query-p">Test-ba</p></div>
<p id="query-show0">TEST-SHOW</p>
<p id="child"></p>
</div>
Note : elements with class "show" have display none
I tried doing this with jquery but I'm just began learning jquery yesterday and it didn't work (I had the same problem as this).
Jquery code I tried : https://pastebin.com/cBisCmEZ
Thank you for your help.

Here is the solution for you
$("p[data-id]").on("click", function() {
var idFound = $(this).data("id");
$("[data-pre='"+ idFound +"']").toggleClass("show");
});
pre {
display:none;
}
.show {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p data-id="p1">This is the paragraph</p>
<pre data-pre="p1">This is the pre<pre>
I recommend using a button element for anything you click so that it stays accessible.

Related

How do I remove a specific div out of many using one function in JavaScript?

I'm learning JavaScript and this is a practice scenario for me.
What I have already is a button that clones content, and within that content that has been cloned, there is a button to remove it.
When I click the button that prompts you to remove the content, it removes the first set of content.
What I want to happen is when you click the button that prompts you to remove the content, it removes the content related to that button and nothing else.
This is the CodePen link.
https://codepen.io/JosephChunta/pen/YzwwgvQ
Here is the code.
function addContent() {
var itm = document.getElementById("newContent");
var cln = itm.cloneNode(true);
document.getElementById("placeToStoreContent").appendChild(cln);
}
function removeContent() {
var x = document.getElementById("content").parentNode.remove();
}
// This is for debug purposes to see which content is which
document.getElementById('orderContent')
.addEventListener('click', function(e) {
const orderedNumber = document.querySelectorAll('.thisIsContent');
let i = 1;
for (p of orderedNumber) {
p.innerText = '' + (i++);
}
});
.contentThatShouldBeHidden {
display: none;
}
<div id="placeToStoreContent">
</div>
<button id="orderContent" onclick="addContent()">Add Content</button>
<div class="contentThatShouldBeHidden">
<div id="newContent">
<div id="content">
<p class="thisIsContent">This is a prompt</p>
<button onclick="removeContent()">Remove this</button>
<hr />
</div>
</div>
</div>
When you'r trying to remove by ID, it takes the first ID it finds.
To remove the correct content, send this onclick.
<button onclick="removeContent(this)">Remove this</button>
And handle it in your function:
function removeContent(el) {
el.parentNode.remove();
}
Example:
function addContent() {
var itm = document.getElementById("newContent");
var cln = itm.cloneNode(true);
document.getElementById("placeToStoreContent").appendChild(cln);
}
function removeContent(el) {
el.parentNode.remove();
}
// This is for debug purposes to see which content is which
document.getElementById('orderContent')
.addEventListener('click', function(e) {
const orderedNumber = document.querySelectorAll('.thisIsContent');
let i = 1;
for (p of orderedNumber) {
p.innerText = '' + (i++);
}
});
.contentThatShouldBeHidden { display: none; }
<div id="placeToStoreContent">
</div>
<button id="orderContent" onclick="addContent()">Add Content</button>
<div class="contentThatShouldBeHidden">
<div id="newContent">
<div id="content">
<p class="thisIsContent">This is a prompt</p>
<button onclick="removeContent(this)">Remove this</button>
<hr />
</div>
</div>
</div>
In your remove button, do this:
<!-- The "this" keyword is a reference to the button element itself -->
<button onclick="removeContent(this)">Remove this</button>
And in your javascript:
function removeContent(element) {
element.parentNode.remove();
}

Problems with javascript event handler

I'm hoping this doesn't get marked as "duplicate", because I have reviewed several threads and followed the advice I found. I know I'm missing something simple, and need other eyes on this. I'm a newbie, so please bear with me. I am testing a simple button element that I have a click event handler on, but it is not working. It works inline with "onclick", but I am trying to avoid that. The simple html:
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>
And the javascript:
<script>
document.getElementById("handler").addEventListener("click", display, true);
function display() {
if (document.getElementById("stringText").style.display === "block") {
document.getElementById("stringText").style.display = "none";
} else {
document.getElementById("stringText").style.display = "block";
}
};
</script>
I have the css that initially sets the "stringText" display as "none". I appreciate any assistance.
Probably your problem is related to the execution of that script while the document is being loaded.
Add this condition stringText.style.display === "" to show/hide the elements correctly.
An alternative is using the event DOMContentLoaded
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
document.getElementById("handler").addEventListener("click", display, true);
function display() {
var stringText = document.getElementById("stringText");
if (stringText.style.display === "block" || stringText.style.display === "") {
stringText.style.display = "none";
} else {
stringText.style.display = "block";
}
};
});
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>
Please allow some delay to load the pages using window.onload events
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>
<script>
window.onload = function(){
document.getElementById("handler").addEventListener("click", display, true);
};
function display() {
if (document.getElementById("stringText").style.display === "block") {
document.getElementById("stringText").style.display = "none";
} else {
document.getElementById("stringText").style.display = "block";
}
};
</script>
If you make sure and set the initial display property to block it works fine. As an alternative, you could also try using jQuery, as I have in the snippet.
//with jquery
$(document).ready(function() {
$('#handler').on('click', function() {
$('#stringText').toggleClass('hide');
})
})
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>

Uncaught TypeError: contentEditable is not a function

I am trying to create a button with a function that will enable or disable contenteditable for all <div>'s however I get that contentEditable is not a function, anyone know why?
function contentEditable() {
var x = document.getElementsByClassName("editable");
if ($(this).attr("contentEditable") == "true") {
console.log=(hello);
x.setAttribute('contentEditable', 'true');
button.innerHTML = "Enable content of p to be editable!";
} else {
x.setAttribute('contentEditable', 'false');
button.innerHTML = "Disable content of p to be editable!";
}
}
<button onclick="contentEditable(this);" id="contentEdit" class="btn btn-primary form-control margin">Edit Text</button>
So many issues I'll just post an annotated example.
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<!-- make sure contenteditable is set to false initially -->
<div class="editable" contenteditable="false">some text 1</div>
<div class="editable" contenteditable="false">some text 2</div>
<div class="editable" contenteditable="false">some text 3</div>
<button id="contentEdit" class="btn btn-primary form-control margin">Edit Text</button>
<script>
var button = document.querySelector('#contentEdit');
var contentEditable = function contentEditable() {
// getElementsByClassName returns a nodelist,so we ahve to cast it to an array, or use a basic for-loop.
var editables = Array.prototype.slice.call(document.getElementsByClassName("editable"));
editables.forEach(function( x ) {
// We want to check the <div> tag for editable, not the button
// the correct attribute is lowercase contenteditable
if (x.getAttribute("contenteditable") === 'false') {
// fixed syntax
console.log("hello");
x.setAttribute('contenteditable', 'true');
// swicthed around Disable and Enable in the strings to make the logic correct.
button.innerHTML = "Disable content of p to be editable!";
} else {
x.setAttribute('contenteditable', 'false');
button.innerHTML = "Enable content of p to be editable!";
}
});
};
button.addEventListener("click", contentEditable);
</script>
</body>
</html>
Make sure contentEditable function loaded inside the page and its not defined inside any other function. Try to execute contentEditable function from chrome or firebug console.
Aside from other errors you have in your code, main issue was your function is not accessible. here's a fiddle where I've put contentEditable() in document, so using it in button <button onclick="document.contentEditable()">
document.contentEditable = function() {
var divs = $("div.editable"),
button = $("#btn"),
attr;
divs.each(function(index, item) {
attr = $(this).attr('contentEditable');
$(this).attr('contentEditable', attr == 'true' ? 'false' : 'true');
});
button.html(attr == 'true' ? 'Disable' : 'Enable');
//console.log(divs);
}
div.editable {
width: 150px;
height: 50px;
margin: 10px;
}
[contentEditable="true"] {
background: black;
}
[contentEditable="false"] {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable="true" class="editable"></div>
<div contentEditable="true" class="editable"></div>
<div contentEditable="true" class="editable"></div>
<div contentEditable="true" class="editable"></div>
<div contentEditable="true" class="editable"></div>
<button id="btn" onclick="document.contentEditable();">Disable</button>
But since you already are using Jquery, why not use something like:
$(":button")//you can use any selector for your button, id perhaps?
.on('click', function() { //your code... });
you have missed to pass the parameter into you function definition:
function contentEditable(obj) {
// replace all this with obj
var x = document.getElementsByClassName("editable");
if ($(obj).attr("contentEditable") == "true") {
console.log=(hello);
x.setAttribute('contentEditable', 'true');
button.innerHTML = "Enable content of p to be editable!";
} else {
x.setAttribute('contentEditable', 'false');
button.innerHTML = "Disable content of p to be editable!";
}
}

Use two or more Buttons to Show/hide and replace text in single DIV

I'm building an about us page and I'm hoping to use JavaScript to show/hide/replace a DIV's content with a vision statement or a bio depending on which is clicked by the user. I'm brand new to using script, so I'm hoping there is someone who has done this before.
I currently have a button for the bio and one for the vision and while I'm able to show and hide text with no problem I have no clue how to replace the DIV so that the Bio and Vision don't show at the same time.
Here is what I have so far:
function showhide(id) {
var e = document.getElementById(id);
e.style.display = (e.style.display == 'block') ? 'none' : 'block';
}
<button type="button" onclick="javascript:showhide('vision')">Vision</button>
<button type="button" onclick="javascript:showhide('bio')">Bio</button>
<div id="vision" style="display: none;">
<p>This is my vision</p>
</div>
<div id="bio" style="display: none;">
<p>This is my bio</p>
</div>
I'd also like the button text to change to "Hide Bio" or "Hide Vision" depending on which is revealed as well.
If anyone could help with this it would be GREATLY appreciated for a Java Noob like me.
This is also my first time using a forum like this so any pointers or feedback is appreciated...gotta start somewhere, right?
UPDATE - I attached an image to give a better idea of what I'm try to accomplish.
There are a couple of issues with logic. If you show/hide one div, you'll still need to hide/show the second div. So you can either add more lines of code to do that.. or simply you can use one div and update its content based on the button clicked.
so you can try this:
<script>
var textStrings = {"author1": {"Vision":"this is author1 vision", "Bio":"this is author1 bio"},
"author2": {"Vision":"this is author2 vision", "Bio":"this is author2 bio"},
"author3": {"Vision":"this is author3 vision", "Bio":"this is author3 bio"}};
function showhide(element) {
reset();
var id=element.id;
var author = document.getElementById("authors").elements["authors"].value;
var flag = document.getElementById('content').innerHTML == textStrings[author][id];
document.getElementById('content').innerHTML = flag ? "" : textStrings[author][id];
element.innerHTML = flag ? id : "hide " + id;
}
function reset(){
for (var k in textStrings["author1"]){
document.getElementById(k).innerHTML = k;
}
}
function resetAuthor(){
document.getElementById('content').innerHTML = ""
reset();
}
</script>
<form id="authors">
<input type="radio" name="authors" id="author1" onchange="resetAuthor()" value="author1" checked> author 1
<input type="radio" name="authors" id="author2" onchange="resetAuthor()" value="author2"> author 2
<input type="radio" name="authors" id="author3" onchange="resetAuthor()" value="author3"> author 3
</form>
<div style="display:inline">
<button type="button" id="Vision" onclick="javascript:showhide(this)">Vision</button>
<button type="button" id="Bio" onclick="javascript:showhide(this)">Bio</button>
</div>
<div style="display: block;">
<p id="content"></p>
</div>
This code also toggles/set contents as empty if you hit the button again.
DEMO
Try to pass the this object into the inline event handler and check the content's display state to toggle the button's text,
HTML:
<button type="button" onclick="javascript:showhide('vision',this)">Vision</button>
<button type="button" onclick="javascript:showhide('bio',this)">Bio</button>
<div id="vision" style="display: none;">
<p>This is my vision</p>
</div>
<div id="bio" style="display: none;">
<p>This is my bio</p>
</div>
JS
function showhide(id,elem) {
var e = document.getElementById(id);
var cond = (e.style.display == 'block');
e.style.display = cond ? 'none' : 'block';
elem.textContent = (id == "vision") ? (cond ? "Show Vision" : "Hide Vision")
: (cond ? "Show Bio" : "Hide Bio");
}
DEMO
Try this out.
var prevPage = "";
var currPage = "";
function showhide(event) {
prevPage = currPage;
currPage = event.id.split("_")[1];
if(prevPage !== currPage){
showEle(currPage);
if(prevPage !== ''){
hideEle(prevPage);
}
} else {
toggle(currPage);
}
}
function toggle(id){
var curr = document.getElementById(id);
if(curr.style.display === 'block'){
curr.style.display = 'none';
updateBtn('btn_'+id, 'Show');
} else {
curr.style.display = 'block';
updateBtn('btn_'+id, 'Hide');
}
}
function updateBtn(id, newStr){
var btn = document.getElementById(id);
btn.innerHTML = newStr + ' ' + btn.innerHTML.split(' ')[1];
}
function showEle(id){
document.getElementById(id).style.display = 'block';
updateBtn('btn_'+id, 'Hide');
}
function hideEle(id){
document.getElementById(id).style.display = 'none';
updateBtn('btn_'+id, 'Show');
}
<button id="btn_vision" type="button" onclick="showhide(this)">Show Vision</button>
<button id="btn_bio" type="button" onclick="showhide(this)">Show Bio</button>
<button id="btn_xyz" type="button" onclick="showhide(this)">Show Xyz</button>
<button id="btn_abc" type="button" onclick="showhide(this)">Show Abc</button>
<div id="vision" style="display: none;">
<p>This is my vision</p>
</div>
<div id="bio" style="display: none;">
<p>This is my bio</p>
</div>
<div id="xyz" style="display: none;">
<p>This is my xyz</p>
</div>
<div id="abc" style="display: none;">
<p>This is my abc</p>
</div>
Note: You might want to initialize the currPage with the first page's id since it gives a better feel.
Say currPage = "vision" and also make display block for div id = "vision".

is it possible to hide div when another button is click?

I am trying to hide the div's when different buttons are clicked but I don't know how to. (So when 'Test 1' is clicked it should hide 'Test 2' Div and vice versa) I checked here and on Google but couldn't find an answer for it.
Javascript :
function showHide(divId) {
var theDiv = document.getElementById(divId);
if (theDiv.style.display == "none") {
theDiv.style.display = "";
} else {
theDiv.style.display = "none";
}
}
HTML :
<input type="button" onclick="showHide('hidethis')" value="Test It">
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
JSFIDDLE: is not doing it here but works locallyhttp://jsfiddle.net/S5JzK/
<input type="button" onclick="showHide('hidethis')" value="Test It" />
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
function showHide(divId) {
$("#"+divId).toggle();
}
Check the Fiddle http://jsfiddle.net/S5JzK/7/
Please try this, it works well and so simple,
<html>
<head>
<style>
.manageDiv{
display:none;
}
</style>
</head>
<body>
<input type="button" class="testButton" value="Test It" />
<input type="button" class="testButton" value="Test It 2" />
<div id="hidethis2" class="manageDiv">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
</body>
</html>
$(function(){
$(".testButton").on("click", function(){
$("#hidethis2").toggleClass("manageDiv");
});
});
To it work in fiddle, in your example, you need to select (No wrap - in head) on the left.
Look the example below, using pure javascript:
HTML
<input type="button" onclick="showHide('hidethis')" value="Test It">
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
JAVASCRIPT
function showHide(divId) {
/* Hide all divs */
var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = "none";
}
/* Set display */
var theDiv = document.getElementById(divId);
theDiv.style.display = "";
}
http://jsfiddle.net/S5JzK/9/
ANOTHER JAVASCRIPT EXAMPLE
function showHide(divId) {
/* Hide the divs that you want */
var div1 = document.getElementById('#hidethis');
var div2 = document.getElementById('#hidethis2');
div1.style.display = "none";
div2.style.display = "none";
/* Set display */
var theDiv = document.getElementById(divId);
theDiv.style.display = "";
}
Using JQuery:
function showHideDiv(divId, bShow) {
if (bShow) {
$("#" + divId).show();
} else {
$("#" + divId).hide();
}
}
your code seems fine. are you sure you enter the function upon click? try adding a breakpoint using developer tools or an alert.
Anyways, I see you tagged this post with jquery. you can you it to do the task more elegantly.
$("#" + theDiv).hide();
or for showing it:
$("#" + theDiv).show();
"JSFIDDLE: is not doing it here but works locally"
Yes, because by default jsfiddle wraps your JS in an onload handler, which means the function declaration is local to that handler. Inline html attribute event handlers like your onclick="showHide('hidethis')" can only call global functions.
Under jsfiddle's Frameworks & Extensions heading there's a drop-down where you can change the default "onload" to "No wrap - in head" (or "No wrap - in body"). That'll make your function declaration global as in your local implementation.
Demo: http://jsfiddle.net/S5JzK/8/

Categories

Resources