Translate javascript function into JQuery - javascript

I have the following function which I have used for hiding and showing respective pages based on different button clicks. Now I am using JQuery and I want to be able to do the same thing but just with JQuery. There must be something wrong the way I am translating it cause it doesn't work.
function showPages() {
var aBtnShowPages = document.getElementsByClassName("btnShowPage");
// this is an array
for (var i = 0; i < aBtnShowPages.length; i++) {
aBtnShowPages[i].addEventListener("click", function () {
//console.log( "WORKS" );
// Hide the pages
var aPages = document.getElementsByClassName("page");
for (var j = 0; j < aPages.length; j++) {
aPages[j].style.display = "none";
}
var sDataAttribute = this.getAttribute("data-showThisPage");
//console.log( sDataAttribute );
document.getElementById(sDataAttribute).style.display = "flex";
});
}
}
JQuery version:
function showPages() {
let $aBtnShowPages = $(".btnShowPage");
// this is an array
for (let i = 0; i < $aBtnShowPages.length; i++) {
$aBtnShowPages[i].click(function () {
//console.log("WORKS");
// Hide the pages
let $aPages = $('.page');
for (let j = 0; j < $aPages.length; j++) {
$aPages[j].hide();
}
let $sDataAttribute = $(this).attr("data-showThisPage");
//console.log( $sDataAttribute );
$(sDataAttribute).show();
});
}
}

This shows how to toggle between those with "false" and those with "true" values. Pretty verbose and could simply be one function using .toggle(true) instead.
I put some fake markup in place since you provided none.
$(function() {
$(".btnShowPage").on("click", function() {
let $aPages = $('.page');
$aPages.hide();
$aPages.filter(function() {
return $(this).data("showThisPage") == true;
}).show();
}).trigger('click'); // set initial state ;
$(".btnHidePage").on("click", function() {
let $aPages = $('.page');
$aPages.show();
$aPages.filter(function() {
return $(this).data("showThisPage") == true;
}).hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="page" data-show-this-page="true">showme1</div>
<div class="page" data-show-this-page="true">showme2</div>
<div class="page" data-show-this-page="true">showme3</div>
<div class="page" data-show-this-page="false">showme4</div>
<div class="page" data-show-this-page="true">showme5</div>
<div class="page" data-show-this-page="true">showme6</div>
<button id="showem" class="btnShowPage" type="button">showem</button>
<button id="hideem" class="btnHidePage" type="button">hideem</button>
Just show those with true set.
$(function() {
$(".btnShowPage").on("click", function() {
// just show those with true set
$('.page').each(function(index) {
let showme = $(this).data("showThisPage") == true;
$(this).toggle(showme);
});
}).trigger('click'); // set initial state ;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="page" data-show-this-page="true">showme1</div>
<div class="page" data-show-this-page="true">showme2</div>
<div class="page" data-show-this-page="true">showme3</div>
<div class="page" data-show-this-page="false">showme4</div>
<div class="page" data-show-this-page="true">showme5</div>
<div class="page" data-show-this-page="true">showme6</div>
<button id="showem" class="btnShowPage" type="button">showem</button>
Show just a targeted element and hiding/showing all:
$(function() {
$(".btnShowPage").on("click", function() {
// just show those with the target
let showTarget = $(this).data("target");
switch (showTarget) {
case -1:
$('.page').hide();
break;
case "all":
$('.page').show();
break;
default:
$('.page').eq(showTarget).toggle(true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="page">showme0</div>
<div class="page">showme1</div>
<div class="page">showme2</div>
<div class="page">showme3</div>
<div class="page">showme4</div>
<div class="page">showme5</div>
<div class="page">showme6</div>
<button id="showem" class="btnShowPage" type="button" data-target="all">showem all</button>
<button id="showem" class="btnShowPage" type="button" data-target="1">showem 1</button>
<button id="showem" class="btnShowPage" type="button" data-target="2">showem 2</button>
<button id="showem" class="btnShowPage" type="button" data-target="5">showem 5</button>
<button id="showem" class="btnShowPage" type="button" data-target="-1">hide all</button>

Related

Cloning elements with their events not working

I am cloning a div using jQuery and find that events on cloned elements do not work although they work on the original elements. How can I go about this? Note how the answer in the question states that...
"This is how jQuery's clone() method is able to copy a node with its
event listeners, for example"
let add = document.getElementsByClassName("add"),
rem = document.getElementsByClassName("rem"),
container = document.getElementsByClassName('container')[0];
for (let i = 0; i < add.length; i++) {
add[i].addEventListener("click", () => {
$(".cloneable").clone(true, true).appendTo(".container");
});
}
for (let i = 0; i < rem.length; i++) {
rem[i].addEventListener("click", () => {
if (container.childElementCount > 1) {
$(".cloneable:last").remove();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="cloneable">
<div>
<a class="btn btn-primary add" role="button">Add cell</a>
<a class="btn btn-primary rem" role="button">Remove cell</a>
</div>
<iframe src="index.php"></iframe>
</div>
</div>
ETA: This code clones all elements named ".cloneable", so on second click it creates TWO clones, and so on. You should clone with $('.cloneable:first') or similar.
The issue seems to arise from you binding javascript native events. Using jQuery Events solves your problem.
let add = document.getElementsByClassName("add"),
rem = document.getElementsByClassName("rem"),
container = document.getElementsByClassName('container')[0];
for (let i = 0; i < add.length; i++) {
$(add[i]).on("click", () => {
$(".cloneable:first").clone(true, true).appendTo(".container");
});
}
for (let i = 0; i < rem.length; i++) {
$(rem[i]).on("click", () => {
if (container.childElementCount > 1) {
$(".cloneable:last").remove();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="cloneable">
<div>
<a class="btn btn-primary add" role="button">Add cell</a>
<a class="btn btn-primary rem" role="button">Remove cell</a>
</div>
<iframe src="index.php"></iframe>
</div>
</div>

How to simplify this code shared in image below?

I want to show div content on button click .and thee is 3 different button following 3 different content. I tried this logic and it made my code lengthy. how to simplify is code using loop or condition?
function replace1(){
document.getElementById("con1").style.visibility="visible";
document.getElementById("con2").style.visibility="hidden";
document.getElementById("con3").style.visibility="hidden";
document.getElementById("con4").style.visibility="hidden";
document.getElementById("con5").style.visibility="hidden";
document.getElementById("con6").style.visibility="hidden";
}
function replace2(){
document.getElementById("con1").style.visibility="hidden";
document.getElementById("con2").style.visibility="visible";
document.getElementById("con3").style.visibility="hidden";
document.getElementById("con4").style.visibility="hidden";
document.getElementById("con5").style.visibility="hidden";
document.getElementById("con6").style.visibility="hidden";
}
function replace3(){
document.getElementById("con1").style.visibility="hidden";
document.getElementById("con2").style.visibility="hidden";
document.getElementById("con3").style.visibility="visible";
document.getElementById("con4").style.visibility="hidden";
document.getElementById("con5").style.visibility="hidden";
document.getElementById("con6").style.visibility="hidden";
}
enter image description here
.active-button {
background: red;
}
<button class="replace-button" onclick="replace(1, this)"></button>
<button class="replace-button" onclick="replace(2, this)"></button>
<button class="replace-button" onclick="replace(3, this)"></button>
function replace(visibleIndex, _this) {
const buttons = document.querySelectorAll('.replace-button');
buttons.forEach(button => button.classList.remove("active-button"));
_this.classList.add("active-button");
for(let i = 1; i < 7; i++) {
let element = document.getElementById("con" + i)
i === visibleIndex ? element.style.visibility = "visible" : element.style.visibility = "hidden";
}
}
Use a class - add class="con" to each element - also use hidden instead of visibility since the hidden divs still will take up space
const toggle = id => cons
.forEach(con => con.hidden = con.id !== id);
Here is a version that will change the colour of the button too.
You will need to use hidden or display:none to have the divs stay in one place
window.addEventListener('DOMContentLoaded', function() {
const cons = document.querySelectorAll('.con');
const buts = document.querySelectorAll('.toggle');
const toggle = id => cons
.forEach(con => con.hidden = con.id !== id);
document.getElementById('nav').addEventListener('click', function(e) {
const tgt = e.target.closest('button');
if (tgt.classList.contains('toggle')) {
toggle(tgt.dataset.id)
buts.forEach(but => but.classList.remove('active'));
tgt.classList.add('active');
}
})
})
.active {
background-color: green;
}
<nav id="nav">
<button type="button" class="toggle" data-id="con1">Con 1</button>
<button type="button" class="toggle" data-id="con2">Con 2</button>
<button type="button" class="toggle" data-id="con3">Con 3</button>
</nav>
<div id="con1" class="con" hidden>
<h1>Con 1</h1>
</div>
<div id="con2" class="con"hidden>
<h1>Con 2</h1>
</div>
<div id="con3" class="con" hidden>
<h1>Con 3</h1>
</div>

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();
}

get position of an element and display a div after it with javascript

I have 10 different buttons and i want to show a hidden div exactly down from the button the user pressed.the div is currenlty showing exactly at the block the code of div is istead of taking new cords top: left:
THE function call:
<img style="position:relative;float:right;padding-top:7px;" onclick="find_pos(this)" src="images/view_comments.png"></li></a>
function find_pos(ele) {
var x=0;
var y=0;
while(true){
x += ele.offsetLeft;
y += ele.offsetTop;
if(ele.offsetParent === null){
break;
}
ele = ele.offsetParent;
}
hidden_comment_form.style.display='block';
hidden_comment_form.style.top=y;
hidden_comment_form.style.left=x;
}
I give you 2 options :
option 1 :
<div class="main">
<button class="btn">a</button>
<div class="toggle"> a toggle this </div>
</div>
<div class="main">
<button class="btn">b</button>
<div class="toggle"> b toggle this </div>
</div>
<script>
$(document).ready(function() {
$('button.btn').on('click', function() {
var $div = $(this).siblings('.toggle');
$div.toggle();
})
})
</script>
option 2:
<button class="btn">a</button>
<div class="toggle"> a toggle this </div>
<button class="btn">b</button>
<div class="toggle"> b toggle this </div>
<script>
$(document).ready(function() {
$('button.btn').on('click', function() {
var $div = $(this).next();
$div.toggle();
})
})
</script>
i suggest option 1 is better

Multiple div popups

I have a JavaScript to open a DIV as popup.
But now I want to open several different popups from different DIVS and I can't get it to work properly.
I use the following JavaScript:
<script>
window.onload = function()
{
var show = document.getElementById('show-div');
var hide = document.getElementById('hide-div');
var popup = document.getElementById('popup-div');
show.onclick = function(e)
{
popup.style.visibility = 'visible';
return false;
}
hide.onclick = function(e)
{
popup.style.visibility = 'hidden';
return false;
}
}
</script>
and for the div I use the followin code:
<a id="show-div" href="#">link</a>
<div id="popup-div">
<div id="popup-header">
<div id="popup-title">...Popup title...</div>
<a id="hide-div" href="#">X</a></div>
<div id="popup-body">
<p>This is the content of the div....</p>
</div>
</div>
This works for 1 link but even when I use a different DIV ID's (and associated var element like "var popup1 = document.getElementById('popup-div1');" and popup1 onclick events) I can't get it work properly.
How can I make it work with several links with all it's own DIV with content.
(as I can't answer my own question, here is how I fixed it)
I made it work with the following code:
<script>
window.onload = function()
{
var show = document.getElementById('show-div');
var show2 = document.getElementById('show-div2');
var hide = document.getElementById('hide-div');
var hide2 = document.getElementById('hide-div2');
var popup = document.getElementById('popup-div');
var popup2 = document.getElementById('popup-div2');
show.onclick = function(e)
{
popup.style.visibility = 'visible';
return false;
}
show2.onclick = function(e)
{
popup2.style.visibility = 'visible';
return false;
}
hide.onclick = function(e)
{
popup.style.visibility = 'hidden';
return false;
}
hide2.onclick = function(e)
{
popup2.style.visibility = 'hidden';
return false;
}
}
</script>
and
<a id="show-div" href="#">link</a>
<div id="popup-div">
<div id="popup-header">
<div id="popup-title">...Popup title...</div>
<a id="hide-div" href="#">X</a></div>
<div id="popup-body">
<p>This is the content of the div....</p>
</div>
</div>
<a id="show-div2" href="#">link2</a>
<div id="popup-div2">
<div id="popup-header">
<div id="popup-title">...Popup title2...</div>
<a id="hide-div2" href="#">X</a></div>
<div id="popup-body">
<p>This is the content of the div2....</p>
</div>
</div>
I believe following is that you want....
Demo
JS Code:
var show = document.getElementById('show-div');
var hides = document.getElementsByClassName('hide-div');
var popups = document.getElementsByClassName("popup-div");
show.onclick = function (e) {
for (var i = 0; i < popups.length; i++) {
popups[i].style.visibility = 'visible';
}
return false;
}
for (var j = 0; j < hides.length; j++) {
hides[j].onclick = function (e) {
this.parentNode.parentNode.style.visibility = 'hidden';
return false;
}
}
HTML Code:
<a id="show-div" href="#">Show/Hide</a>
<div id="popup-div" class="popup-div">
<div id="popup-header">
<div id="popup-title">...Popup title...</div>
<a id="hide-div" class="hide-div" href="#">X</a>
</div>
<div id="popup-body">
<p>This is the content of the div....</p>
</div>
</div>
<div id="popup-div" class="popup-div">
<div id="popup-header">
<div id="popup-title">...Popup title...</div>
<a id="hide-div" class="hide-div" href="#">X</a>
</div>
<div id="popup-body">
<p>This is the content of the div....</p>
</div>
</div>

Categories

Resources