Switching the divs via script in wordpress - javascript

I have the following code to switch between 2 divs:
<script>
function SwapDivsWithClick(div1,div2)
{
d1 = document.getElementById(div1);
d2 = document.getElementById(div2);
if( d2.style.display == "none" )
{
d1.style.display = "none";
d2.style.display = "block";
}
else
{
d1.style.display = "block";
d2.style.display = "none";
}
}
var divs = [ "zdroj1", "zdroj2" ];
function toggle(layer) {
var d
for(var i = 0; i < divs.length; i += 1) {
d = document.getElementById(divs[i]);
d.style.display = 'none';
}
d = document.getElementById(layer);
d.style.display = '';
}
</script>
And the HTML part:
<table>
<tbody>
<tr>
<td class="btn" style="text-align: center;"><a href="javascript:toggle('zdroj1')" ><b>VIDEO 1</b></a></div></td>
<td class="btn" style="text-align: center;"><a href="javascript:toggle('zdroj2')" ><b>VIDEO 2</b></a></div></td>
</tr>
</tbody>
</table>
<div id="zdroj1">
VIDEO CODE 1</div>
<div id="zdroj2" style="display:none;">
VIDEO CODE 2</div>
How can I add more divs and show only that one which link is clicked? I think that there must be more if functions in the script but I am not sure, because I am a newbie in this part of coding. Thanks in advance!

Edit: Based on your needs to have a dynamic amount of divs/buttons on each page see the code below. Instead of manually creating the click eventListener you need to get an array(-ish) of the buttons based on a common class name (querySelector could also be used for this) and add the event listener to each. The buttons should be created with a data-attribute (or other identifier) that corresponds to one of the divs you want to toggle.
Inside the function that is called you can loop through all your msg divs, hide them all and unhide the one that matches the data-attribute of the button that was clicked. This method allows you to have any number of buttons and divs as long as each button has a matching div for it to toggle.
// Find all the buttons and divs that have the common className for each
var buttons = document.getElementsByClassName('button')
var divs = document.getElementsByClassName('msg')
function toggle() {
// Loop through the divs and hide them all
for(var i = 0; i < divs.length; i += 1) {
divs[i].style.display = 'none';
}
// Show the div whose id matches the data-message attribute of the button that was clicked
document.getElementById(this.dataset.message).style.display = 'block';
}
// Add a click listener to each button to run the toggle function
for(var i = 0; i < buttons.length; i += 1) {
buttons[i].addEventListener('click', toggle, false)
}
<table>
<tbody>
<tr>
<!-- Add a common class to all buttons and a data-message attribute to each button
that corresponds to the id of the div it will toggle on-->
<td class="btn"><button class="button" data-message="msg1">VIDEO 1</button></td>
<td class="btn"><button class="button" data-message="msg2">VIDEO 2</button></td>
<td class="btn"><button class="button" data-message="msg3">VIDEO 3</button></td>
<td class="btn"><button class="button" data-message="msg4">VIDEO 3</button></td>
</tr>
</tbody>
</table>
<!-- Add a common class to all divs that will be toggled -->
<div class="msg" id="msg1">
VIDEO CODE 1
</div>
<div class="msg" id="msg2" style="display:none;">
VIDEO CODE 2
</div>
<div class="msg" id="msg3" style="display:none;">
VIDEO CODE 3
</div>
<div class="msg" id="msg4" style="display:none;">
VIDEO CODE 4
</div>

Related

Javascript search with includes for each DIV

I am trying to develop a filter function with includes. As for now, I have 3 main DIV, and each main DIV has its own DIV. The current script I have now only worked on main DIV.
Instead of highlighting main DIV, I only want to highlight matched char DIV.
For example, when key in 'inner', Inner First and Inner Sec will be highlighted. When key in 'Inner First', only DIV for Inner First will be highlighted.
Would appreciate if anyone of you can help me. Thanks in advance.
function myFunction() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
for (i = 0; i < nodes.length; i++) {
nodes[i].style.backgroundColor = "";
if (input.value !== '') {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
nodes[i].style.backgroundColor = "blue";
for (j = 0; j < nodes[i].length; j++) {
nodes[j].style.backgroundColor = "";
if (input.value !== '') {
if (nodes[j].innerText.toLowerCase().includes(filter)) {
nodes[j].style.backgroundColor = "grey";
for (k = 0; k < nodes[j].length; k++) {
nodes[k].style.backgroundColor = "";
if (input.value !== '') {
if (nodes[k].innerText.toLowerCase().includes(filter)) {
nodes[k].style.backgroundColor = "yellow";
} else {
nodes[k].style.backgroundColor = "red";
}
}
}
} else {
nodes[j].style.backgroundColor = "red";
}
}
}
} else {
nodes[i].style.backgroundColor = "red";
}
}
}
}
<table align="center" width="20%">
<tr>
<td style="padding-right: 10px">
<input type="text" id="Search" title="Type in a name">
<button onclick="myFunction()">
Click to search
</button>
</td>
</tr>
</table>
<br>
<div class="target">
This is my DIV element.
<div class="target">
Inner First
<div class="target">
Inner Sec
</div>
</div>
</div>
<div class="target">
This is another Div element.
</div>
<div class="target">
Can you find me?
</div>
The problem with your code is that node.innerText also gives the text of the child elements. To fix this, you should use node.childNodes[0].nodeValue which will only give the node's text.
Moreover, you are doing nested loops but referencing incorrectly:
for (j = 0; j < nodes[i].length; j++).
nodes[i].length here is undefined. Maybe you mean nodes[i].children.length?
Also, your code is hard to follow with all the nested loops which does the same thing and just differ in color. I suggest you make a recursive function.
Please see below function if I what I'm thinking is correct. I guess you wanted to put different colors depending of the level of the node in the heirarchy. (Open your developer tool to see console.log outputs)
var input;
var filter;
var nodes;
var colors;
function myFunction() {
//initialize variables
input = document.getElementById("Search");
filter = input.value.toLowerCase();
nodes = document.getElementsByClassName('target');
// store colors here for accessing via index
colors = ['blue', 'grey', 'yellow', 'green'];
if (filter !== '') {
updateNodesBg(nodes); //neat
}
}
function updateNodesBg(lNodes, colorIdx) {
colorIdx = colorIdx || 0; // this will be the index of the color
for (var i = 0; i < lNodes.length; i++) {
var currentNode = lNodes[i];
var currentText = currentNode.childNodes[0].nodeValue;
var innerText = currentNode.innerText;
console.log('currentText and innerText EQUAL?', currentText === innerText);
if (currentText.toLowerCase().includes(filter)) {
currentNode.style.backgroundColor = colors[colorIdx]; //pass in the index to get the color
} else {
currentNode.style.backgroundColor = 'red'; //else, we should color red
}
if (currentNode.children && currentNode.children.length > 0) {
updateNodesBg(currentNode.children, colorIdx + 1); //if the node has children, call `updateNodesBg` recursively
}
}
}
<table align="center" width="20%">
<tr>
<td style="padding-right: 10px">
<input type="text" id="Search" title="Type in a name">
<button onclick="myFunction()">
Click to search
</button>
</td>
</tr>
</table>
<br>
<div class="target">
This is my DIV element.
<div class="target">
Inner First 1
<div class="target">
Inner Sec 1
<div>Inner Third 1</div>
</div>
<div class="target">
Inner Sec 2
<div>Inner Third 1</div>
<div>Inner Third 2
<div>Inner Fourth 1</div>
</div>
</div>
</div>
<div class="target">
Inner First 2
<div class="target">
Inner Sec 2
<div>Inner Third 2</div>
</div>
</div>
</div>
<div class="target">
This is another Div element.
</div>
<div class="target">
Can you find me?
</div>
Note that .nodeValue has different returns depending on the type of the node:
Node Value of nodeValue
CDATASection Content of the CDATA section
Comment Content of the comment
Document null
DocumentFragment null
DocumentType null
Element null
NamedNodeMap null
EntityReference null
Notation null
ProcessingInstruction Entire content excluding the target
Text Content of the text node
You need to check if the text is in the current div, then in any child divs.
InnerText and textContent both concatenate text of the parent and all children, so you'll need to figure out where the text is actually coming from.
I do this recursively, because I don't think you'll have that many layers of divs. If there is a lot of nesting, then you'd need to take an iterative approach
function myFunction()
{
let targets = document.querySelectorAll('.target');
targets.forEach(target => target.style.background = 'white');
let filterText = document.getElementById('Search').value;
if(filterText != '')
{
let result = [...targets].filter(target => target.textContent.includes(filterText));
result.forEach(r => { checkSelf(r, filterText); checkKids(r, filterText); });
}
}
function checkSelf(element, filterText)
{
let selfText = element.textContent;
for(let child of element.children)
{
selfText = selfText.replace(child.textContent, '');
}
if(selfText.includes(filterText))
{
element.style.background = 'limegreen';
}
else
{
element.style.background = 'white';
}
}
function checkKids(element, filterText)
{
for(let child of element.children)
{
if(!child.textContent.includes(filterText))
{
child.style.background = 'white';
}
else
{
checkKids(child, filterText);
}
}
}
<table align="center" width="20%">
<tr>
<td style="padding-right: 10px">
<input type="text" id="Search" title="Type in a name">
<button onclick="myFunction()">
Click to search
</button>
</td>
</tr>
</table>
<br>
<div class="target">
This is my DIV element.
<div class="target">
Inner First
<div class="target">
Inner Sec
</div>
</div>
</div>
<div class="target">
This is another Div element.
</div>
<div class="target">
Can you find me?
</div>

I have a css navigation bar with three items. I want to make each link show its own content without overlapping the other one

Here is what I have so far, which works fine, but doesn't disappear once another link is activated.
function skillsFunction () {
var x = document.getElementById("mySkills");
if (x.style.display == "none"){
x.style.display = "block"; {}
} else {
x.style.display = "none";
}
}
let openTab = (event, tabNumber) => {
const tabContent = document.getElementsByClassName("tabContent");
for(let tab of tabContent) {
tab.style.display = "none";
}
document.getElementById(tabNumber).style.display = "block";
}
<div class="tabs">
<span class="tab" onclick="openTab(event,1)">Projects</span>
<span class="tab" onclick="openTab(event,2)">Skills</span>
<span class="tab" onclick="openTab(event,3)">Courses</span>
</div>
<div class="mySkills" id="2"></div>
<div class="myCourses" id="3"></div>
<!--START OF PROJECTS WRAPPER-->
<div class="projectsWrapper" id="1">
This is my first time using JavaScript.
Alrighty, first off it is typically not good practice to use HTML onclick="" to handle clicks, so we would rather use JS to attach an event listener.
In the HTML, add the class of tabContent, which was missing, an id to each tab, and add "div" + tabId to each body content (Ids can be whatever you want just keep them the same). Also add display:none to initially start the content closed (probably choose one to start open and leave that without display:none) (And of course change the layout/whatever to fit the rest of your HTML):
Then, in the JS initialize tabs and tabContent, and for each tab add a click event listener which hides every tabContent then displays the one that matches the tabId.
const tabs = document.getElementsByClassName("tab");
const tabContent = document.getElementsByClassName("tabContent");
for(var i = 0; i < tabs.length; i++) {
tabs[i].addEventListener("click", function(event) {
for(var i = 0; i < tabContent.length; i++) {
tabContent[i].style.display = "none";
}
var tabId = event.target.id;
document.getElementById("div" + tabId).style.display = "block";
});
}
<span id="PROJECTS" class="tab">Projects</span>
<span id="SKILLS" class="tab">Skills</span>
<span id="COURSES" class="tab">Courses</span>
<div class="mySkills tabContent" id="divSKILLS" style="display:none">
Skills
</div>
<div class="myCourses tabContent" id="divCOURSES" style="display:none">
Courses
</div>
<div class="projectsWrapper tabContent" id="divPROJECTS" style="display:none">
Projects
</div>
Let me know how it goes!
JsFiddle

JavaScript Hide/Show

I'm developing a project, and the actions (CRUD) are split into forms and divs. The divs have a function (hide/show), but I want to know how can I show just 1 div at a time, because the current function allows to show more than 1 div at a time and I don't want that to happen. The code is just a test.
function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
function myFunction2() {
var x = document.getElementById('myDIV2');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
<html>
<head>
<title>Teste</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js.js"></script>
<table border="1">
<tr>
<td>Teste 1</td>
<td>Teste 2</td>
</tr>
<tr>
<td><a onclick="myFunction()">Show/Hide</button></td>
<td><button onclick="myFunction2()">Show/Hide</button></td>
</tr>
</table>
<div id="myDIV">
<h1>Teste 1</h1>
</div>
<div id="myDIV2">
<h1>Teste 2</h1>
</div>
</body>
</html>
You should hide other DIV, when open another.
Like:
when show DIV = hide DIV2
when show DIV2 = hide DIV
This common example can be treated with jQuery accordion
You can try something like this:
hideAllDivs();
function myFunc(id) {
var x = document.getElementById(id);
if (x.style.display === 'none') {
hideAllDivs();
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
function hideAllDivs() {
var divs = document.getElementsByTagName('div');
if (divs.length > 1) {
for (var i = 0; i < divs.length; i++) {
divs[i].style.display = 'none';
}
}
}
As you have included jQuery in your code, I will give you a jQuery based answer.
You have two buttons:
<button onclick="myFunction()">Show/Hide</button>
<button onclick="myFunction2()">Show/Hide</button>
You can remove the onclick and give them classes instead:
<button class="showhide-1">Show/Hide</button>
<button class="showhide-2">Show/Hide</button>
And you can give the <div>'s you want to Hide/Show a class (which will be myDIVS for the example) and optionally you can use style="display: none;" to hide them both when the page loads.
<div id="myDIV" class="myDIVS" style="display: none;">
<h1>Test 1</h1>
</div>
<div id="myDIV2" class="myDIVS" style="display: none;">
<h1>Test 2</h1>
</div>
Now you just need the jQuery code:
First we need to select the first button using its class, and capture all click events on it, like this:
$('.showhide-1').click(function() {
});
Inside that, you need to 1. Hide #myDIV2 and 2. Show #myDIV.
$('#myDIV2').hide();
$('#myDIV').toggle();
Now just do the same again for the other button:
$('.showhide-2').click(function() {
$('#myDIV').hide();
$('#myDIV2').toggle();
});
$('.showhide-1').click(function() {
$('#myDIV2').hide();
$('#myDIV').toggle();
});
$('.showhide-2').click(function() {
$('#myDIV').hide();
$('#myDIV2').toggle();
});
<html>
<head>
<title>Teste</title>
</head>
<body>
<table border="1">
<tr>
<td>Test 1</td>
<td>Test 2</td>
</tr>
<tr>
<td>
<button class="showhide-1">Show/Hide</button>
</td>
<td>
<button class="showhide-2">Show/Hide</button>
</td>
</tr>
</table>
<div id="myDIV" class="myDIVS" style="display: none;">
<h1>Test 1</h1>
</div>
<div id="myDIV2" class="myDIVS" style="display: none;">
<h1>Test 2</h1>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</body>
</html>

how to pass the text value of one html paragraph element to another html paragraph element using javascript in asp.net

I'm trying to pass the text value of one of my html paragraph element to another html paragraph element when the javascript function is called. When this function is called it will load the div element which has the enlarged image and a paragraph content, that is why I'm passing the value from one html paragraph element text value to another paragraph element text value. Here's my code below for your reference:
Javacript:
<script type="text/javascript">
function LoadDiv(url)
{
var img = new Image();
var bcgDiv = document.getElementById("divBackground");
var imgDiv = document.getElementById("divImage");
var imgFull = document.getElementById("imgFull");
img.onload = function() {
imgFull.src = img.src;
imgFull.style.display = "block";
imgLoader.style.display = "none";
};
img.src= url;
var width = document.body.clientWidth;
if (document.body.clientHeight > document.body.scrollHeight)
{
bcgDiv.style.height = document.body.clientHeight + "px";
}
else
{
bcgDiv.style.height = document.body.scrollHeight + "px" ;
}
imgDiv.style.left = (width-650)/2 + "px";
imgDiv.style.top = "20px";
bcgDiv.style.width="100%";
bcgDiv.style.display="block";
imgDiv.style.display="block";
var artcontent = document.getElementById("TextBox2").value;
document.getElementById("content").value = artcontent;
/* after I added these two lines of codes below which I thought these could pass the value but it just ruined my function and not loading anymore the div element I'm calling,it will now only flash the div element for 1 sec without event displaying the content of the artxt2 html paragraph.*/
var artcon = document.getElementById('artxt1').innerHTML;
document.getElementById('artxt2').innerHTML = artcon;
return false;
}
</script>
Asp.Net Source code:
<div id="divBackground" class="modal">
</div>
<div id="divImage">
<table style="height: 100%; width: 100%">
<tr>
<td valign="middle" align="center">
<img id="imgFull" alt="" src=""
style="display: none;
height: 500px;width: 590px" />
</td>
</tr>
<tr>
<td >
<p id ="artxt2" runat ="server" ></p>
<textarea name = "artcont" id = "content" cols ="0" rows ="0" readonly ="readonly" style ="width :590px; height :100px; color :Blue; font-family :Verdana; display :block;"></textarea>
</td>
</tr>
<tr>
<td align="center" valign="bottom">
<input id="btnClose" type="button" value="close"
onclick="HideDiv()"/>
</td>
</tr>
</table>
</div>
I need someone who can assist me and figure out what I'm missing here..Thanks in advance.
Change the name with id.
artxt1 must be an id of a control not name.
var artcon = document.getElementById('artxt1').innerHTML;
document.getElementById('content').innerHTML = artcon;
Try this -
var artcon = document.getElementById('<%=artxt1.ClientID%>').innerHTML;
document.getElementById('<%=artxt2.ClientID%>').innerHTML = artcon;
When you have runat=server on a control the ID is auto generated by .NET (unless you specifically tell it to use static IDs which I think was only introduced in ASP.NET 4.0)
So you need to use the ClientID property to get the generated ID for the control http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx

show/hide link in javascript

I have 4 links which place under seperate <td>, I want to show/hide the td based on a particular selection of parent object
<td nowrap align=right id="dis_mirr" style="visiblility: visible;">
<a id="first" style=font-weight:normal href=javascript:createwin();>
Mirror
</a>
</td>
<td nowrap align=right>
<a id="second" style=font-weight:normal href=javascript:breakwin();>
Break Mirror
</a>
</td>
here is code:
if(record.get('model') == 'top'){
document.getElementById('first').visibility = "hidden";
}else{
document.getElementById('first').visibility = "visible";
}
The code works but the <td> is still there it should be removed when I hide it.
You have to use the parentNode attribute, which will return the parent element, here the <td> :
if(record.get('model') == 'top'){
document.getElementById('first').parentNode.visibility = "hidden";
} else {
document.getElementById('first').parentNode.visibility = "visible";
}
Try this:
document.getElementById("first").parentNode.style.display = 'none';

Categories

Resources