In the Index file I have these divs which I note by IDs, let's say there are 3 of these:
<div class="col-sm-6 col-md-4 col-lg-3 grid-item" id="one">
<div class="well">
<a href="http://" target="_blank">
<img class="class" src="img/pic.jpg" alt=""/>
</a>
<p></p>
<nav>
<div class="anim-icons">
<ul>
<li>
<a href="#">
<img src="" alt="">
</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
And this is part of the JS file:
var one = document.querySelector("#one");
var two = document.querySelector("#two");
var three= document.querySelector("#three");
const randomButton= document.querySelector("#randomButton");
function Randomizer() {
var array = [one, two, three];
var result = array[Math.floor(Math.random() * array.length)];
console.log(result);
var node = document.createElement("DIV");
node.innerHTML(result);
node.appendChild(result);
document.getElementById("#placeofresult").appendChild(node);
}
randomButton.addEventListener("click", Randomizer, false);
This if where I want that above div to be displayed:
<div>
<button class="btn btn-light" id="randomButton">
press!
</button>
<br>
<div id="placeofresult"> </div>
</div>
If I press the button, I want one of the divs from the Index file displayed in the div on the page where this JS belongs, but I don't know how to append a whole div by an id.
Thank you for your insights in advance!
appendChild will work fine if you need to insert div into another one.
Suppose, there is <div id="one">One</div> which you want to append inside <div id="placeofresult"></div>; you need to do the following
document.getElementById("placeofresult").appendChild(document.getElementById("one"));
or if you want to clone the div with id="one" and insert it, do the following:
const newOne = document.getElementById("one").cloneNode(true);
document.getElementById("placeofresult").appendChild(newOne);
Hope it helps. Revert for any doubts.
A solution for your problem could be to write the three divs you want to display entirely into js like this:
const divs = [
"
<div id="one">
...
</div>
",
"<div id="two">
...
</div>
",
"<div id="three">
...
</div>
"
]
Using your randomButton
randomButton.addEventListener("click", Randomizer, false);
You just have to set the innerHTML of your result div to the corresponding div of the divs array:
function Randomizer() {
var resultHTML = divs[Math.floor(Math.random() * array.length)];
document.getElementById("#placeofresult").innerHTML(resultHTML);
}
Another solution is to set the style of your divs to display none and display only the randomly chosen div after the button click:
Your html:
<div id="placeofresult">
<div id="one" style="display:none">
...
</div>
<div id="two" style="display:none">
...
</div>
<div id="three" style="display:none">
...
</div>
</div>
Your Randomizer:
function Randomizer() {
var array = [one, two, three];
// Set all divs to hidden
array.forEach(function(id){
document.getElementById(id).style.display = "none";
})
var result = array[Math.floor(Math.random() * array.length)];
document.getElementById(result).style.display = "block";
}
Related
I am trying to do logic using javascript, so that if div where class is b-format if innerhtml value is Audio it will hide cart-button div, else it will hide the more-button div. For some reason its not working.
var itemButtons = document.querySelectorAll('.slider-wrapper');
for(var i=0; i<itemButtons.length; i++){
var b_format_element = itemButtons[i].getElementsByClassName("b-format")[0];
var cart_element = itemButtons[i].getElementsByClassName("cart-button")[0];
var more_element = itemButtons[i].getElementsByClassName("more-button")[0];
if(b_format_element.innerHTML == "Audio"){
cart_element.style.display = "none";
} else {
more_element.style.display = "none";
}
}
this is html code
<div class="slider-wrapper">
${#Recommend} // this repeat record
<a class="product" href="#">
<div>
<p class="b-format">Audio</p>
</div>
<div class="product-items cart-button">
<span>Read more</span>
</div>
<div class="product actions product-items more-button">
<span>Read more</span>
</div>
</a>
${/Recommend}
</div>
Not good idea to use the same ID tags over and over in a loop. Instead, use a class name. Also, using querySelector will get you the first matching element. It also looks like you want to cycle through the inner DIVs of the slider-container, rather than cycling through multiple slider containers. I added an inner container .record.
document.querySelectorAll('.slider-wrapper .record').forEach(c => {
let isAudio = c.querySelector('.b-format')?.innerText.trim() === 'Audio';
c.querySelector('.cart-button').style.display = isAudio ? 'none' : 'block';
c.querySelector('.more-button').style.display = !isAudio ? 'none' : 'block';
})
.cart-button {
color: #f00;
}
.more-button {
color: #999;
}
<div class="slider-wrapper">
<div class='record'>
<div>
<p class="b-format">Audio</p>
</div>
<!-- buttom -->
<div class="cart-button">
<span>Les mer</span>
</div>
<div class="more-button">
<span>Les mer</span>
</div>
<!-- button end -->
</div>
<div class='record'>
<div>
<p class="b-format">Not Audio</p>
</div>
<!-- buttom -->
<div class="cart-button">
<span>Les mer</span>
</div>
<div class="more-button">
<span>Les mer</span>
</div>
<!-- button end -->
</div>
</div>
I have a single page site which shows/hides section on click within the viewport.
This is an example of one of the sections:
<section id="question1">
<div class="container-fluid">
<div class="row">
<div class="question-container">
<div class="question-box">
<p>What is the answer to this question?</p>
</div>
</div>
<a href="#">
<div id="cheetah" class="col-xs-12 col-lg-6">
<img src="images/cheetah.jpg" class="img-responsive" />
</div>
</a>
<a href="#">
<div id="hedgehog" class="col-xs-12 col-lg-6">
<img src="images/hedgehog.jpg" class="img-responsive" />
</div>
</a>
</div>
</div>
</section>
The problem I am having is that I don't want section ID's to be the same as the a tag href within it. If that makes sense? This is the jQuery I have already:
$(document).ready(function(){
//ID array
var questionArray = ['#question1', '#question2', '#question3', '#question4', '#question5', '#question6', '#question7', '#question8', '#question9', '#question10'];
//collect sections and place in array
var sectionArray = [];
$('section').each(function(){
sectionArray.push(this);
})
//randomise id array
questionArray.sort(function() {
return 0.5 - Math.random()
});
//Target a elements - attach ID to next question
for(var i = 0; i < sectionArray.length; i++) {
var aEl = $(sectionArray[i]).find('a');
$(aEl).each(function(){
$(this).attr('href', questionArray[i]);
})
}
}
Any help?
EDIT:
Link to codepen: https://codepen.io/samrbrown/full/aLdgYK/
I am trying to use jQuery to get the value of the divs with the classes of more_details_con, more_details_desc and more_details_res and when edit_entry is clicked but I don't think I am traversing the DOM correctly because the alert just says undefined.
The HTML
<div class="details">
<span class="id">1234</span>
<span class="contact">account name</span>
</div>
<div class = "more_details">
<div class = "more_details_btns">
<div class="go_account">Go to Account</div>
<div class="edit_entry">Edit</div>
<div class="delete_entry">Delete</div>
</div>
<div class="container">
<div class="more_details_title">Contact:</div>
<div class="more_details_con">Contact name</div>
<p class="clear"></p>
</div>
<div class="container">
<div class="more_details_title">Description:</div>
<div class="more_details_desc">Actual Description</div>
<p class="clear">
</div>
<div class="container">
<div class="more_details_title">Resolution:</div>
<div class="more_details_res">Actual Resolution</div>
<p class="clear">
</div>
</div>
The jQuery I've tried
$("#results").on("click", ".edit_entry", function() {
var contact = $(this).next(".more_details_con").html();
var desc = $(this).next(".more_details_desc").html();
var res = $(this).next(".more_details_res").html();
alert(contact+desc+res);
});
The issue is because the elements you're looking for are not siblings of the one which raised the event. You instead could use closest() to find the nearest common parent element, .more_details, and then find() to get the element you want. Try this:
$("#results").on("click", ".edit_entry", function() {
var $parent = $(this).closest('.more_details');
var contact = $parent.find(".more_details_con").text();
var desc = $parent.find(".more_details_desc").text();
var res = $parent.find(".more_details_res").text();
console.log(contact, desc, res);
});
Basically I have multiple elements A,B,C,... And they are all "connected" to A1,B1,C1,...
For simplicity and better understanding , lets say A,B,C are personal data about A1,B1,C1 persons (A1,B1,C1 are pictures of those persons).
html looks like :
<div class="personal_data">
<p class="A"> Ronnie </p>
<p class="B"> James </p>
<p class="C"> Dio </p>
</div>
<div class="persons">
<div>
<div>
<div class="A1"> img1 </div>
</div>
</div>
<div>
<div>
<div class="B1"> img2 </div>
</div>
</div>
<div>
<div>
<div class="C1"> img3 </div>
</div>
</div>
</div>
Yes , those divs that contain img are nested like that and the order must not be changed.
p elements are hiddenand are shown in personal_data window according to which person has been clicked.
How can I make it that when one picture is clicked its corresponding p element is shown and the rest of them are hidden , and when I click to another picture it shows another p element and hides previous , and so on?
I tried with jQuery two methods :
$(".A1").click(function () {
$(".A").show();
$(".B").hide();
$(".C").hide(); })
But I immediately abandoned it for obvious reasons. It's ugly and I have more than 3 persons so doing it for every person like this would not be a good practice.
$(".persons div").click(function () {
var index=$(".persons div").index(this);
$(".personal_data p").hide().eq(index).show(); })
Because I don't know all jQuery functions ( and all native javascript functions) I was amazed by the power of these but because of those nested images the index of A that corresponds to the A1 would be ok , but other indexes would not have their pair with persons because the number od divs are not equal , rather then "shifted" by +3. So I tweaked .personal_data with 2 empty p elements after A,B and C so the indexes would align. And it worked but I feel like I am violating something .
Is there a more elegant way for achieving this? I feel my problem is lack of knowledge of all functions that exist inside javascript (and jQuery).
Get the list of matching clickable elements, and the personal data, ahead of time (so we don't have to keep re-querying them):
var clickables = $('.persons > div > div > div[class]');
var data = $('.personal_data p');
Then, when clicked, get the index of the clicked thing in that list, rather than hunt through the DOM:
clickables.click(
function() {
data.hide(); // hide the others
var idx = clickables.index(this);
$(data[idx]).show();
}
);
var clickables = $('.persons > div > div > div[class]');
var data = $('.personal_data p');
clickables.click(
function() {
data.hide();
var idx = clickables.index(this);
$(data[idx]).show();
}
)
.personal_data p {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="personal_data">
<p class="A">Ronnie</p>
<p class="B">James</p>
<p class="C">Dio</p>
</div>
<div class="persons">
<div>
<div>
<div class="A1">img1</div>
</div>
</div>
<div>
<div>
<div class="B1">img2</div>
</div>
</div>
<div>
<div>
<div class="C1">img3</div>
</div>
</div>
</div>
Assuming that you will have this class structure in your page consistently, I did something by comparing the class names. If the class name of the clicked div contains the class name of the p element, then the p will be shown, otherwise they will be hidden :
$(".persons div").click(function () {
var myclassname = $(this).attr('class');
$(".personal_data p").hide().filter(function() {
return myclassname.indexOf($(this).attr('class')) >= 0); //if it contains
}).show();
});
Well, I don't like working with index's in lists. I prefer that you retrieve it when you mount it on the server-side with attributes and id's.
So try the following:
$(document).ready(function () {
$('.personal_data p').on('click', function (event) {
var theTarget = $(this).attr('data-detail');
$('.person-details').removeClass('show'); //remove this line in case you don't want only one at a time
$('#' + theTarget).addClass('show');
});
})
.person-details {
opacity: 0;
}
.person-details.show {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="personal_data">
<p class="A" data-detail="ronnie"> Ronnie </p>
<p class="B" data-detail="james"> James </p>
<p class="C" data-detail="dio"> Dio </p>
</div>
<div class="persons">
<div>
<div>
<div class="A1 person-details" id="ronnie"> img1 </div>
</div>
</div>
<div>
<div>
<div class="B1 person-details" id="james"> img2 </div>
</div>
</div>
<div>
<div>
<div class="C1 person-details" id="dio"> img3 </div>
</div>
</div>
</div>
All the styling or class you can customize. If you prefer showing or hiding , just change the removeClass to hide, and the addClass to show
If you want the oposite interaction :
$(document).ready(function () {
$('.person-details').on('click', function (event) {
var theTarget = $(this).attr('data-detail');
$('.personal_data p').removeClass('show'); //remove this line in case you don't want only one at a time
$('#' + theTarget).addClass('show');
});
})
.personal_data p {
opacity: 0;
}
.personal_data p.show {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="personal_data">
<p class="A" id="ronnie"> Ronnie </p>
<p class="B" id="james"> James </p>
<p class="C" id="dio"> Dio </p>
</div>
<div class="persons">
<div>
<div>
<div class="A1 person-details" data-detail="ronnie"> img1 </div>
</div>
</div>
<div>
<div>
<div class="B1 person-details" data-detail="james" > img2 </div>
</div>
</div>
<div>
<div>
<div class="C1 person-details" data-detail="dio"> img3 </div>
</div>
</div>
</div>
How do I loop thru array keys to output their values to HTML?
The layout I'm working with is a thumbnail grid, 3 columns by 2 rows. Each thumbnail has a caption below it. Selecting any of the thumbnails opens up a hidden container which is also a grid of 3 columns and 2 rows. Within that hidden container many of the images and captions are going to be identical so rather than have a whole bunch of duplicate HTML I figured I could just store each in an array and reference the values that each is associated with. I'm just stuck on how to create the loop at the moment.
var img=[
'image01.jpg','image02.jpg','image03.jpg','image04.jpg'
]
var details=[
'aaaaaa','bbbbbb','cccccc','dddddd'
];
$( "#yin" ).click(function() {
var img = [0,2];
var details = [0,1];
$(step).each(function() {
document.getElementById("img").innerHTML();
});
$(imgs).each(function() {
document.getElementById("img").innerHTML();
});
});
<div class="container">
<ul class="row-fluid">
<li class="span4" id="yin">
<div class="row-fluid">
<img src="yin.jpg" />
<h3>Yin</h3>
</div>
</li>
<li class="span4" id="yang">
<div class="row-fluid">
<img src="yang.jpg" />
<h3>Yang</h3>
</div>
</li>
</ul>
<div class="row-fluid">
<div class="span12">
<div class="show-details details">
<div class="detail-content">
<div id="img">
<!-- Loop (for yin would be image01, and image03) -->
</div>
<div id="details">
<!-- Loop (for yin would be 'aaaaaa','bbbbbb') -->
</div>
</div>
</div>
</div>
</div>
</div>
There's an issue with that code before you get into looping, the img and details variables are being re-declared inside your click function. What are they intended to be? From the comments in your code they seem to be specifying which indices of the array to use.
var images = ['image01.jpg','image02.jpg','image03.jpg','image04.jpg'];
var details = ['aaaaaa','bbbbbb','cccccc','dddddd'];
$( "#yin" ).click(function() {
var imgIndices = [0,2];
var detailIndices = [0,1];
$("#img").html("");
$("#details").html("");
$(imgIndices).each(function(i, o) {
$("#img").append("<img src=\"" + images[o] + "\"/>");
});
$(detailIndices).each(function(i, o) {
$("#details").append("<p>" + details[o] + "</p>");
});
});
<div class="container">
<ul class="row-fluid">
<li class="span4" id="yin">
<div class="row-fluid">
<img src="yin.jpg" />
<h3>Yin</h3>
</div>
</li>
<li class="span4" id="yang">
<div class="row-fluid">
<img src="yang.jpg" />
<h3>Yang</h3>
</div>
</li>
</ul>
<div class="row-fluid">
<div class="span12">
<div class="show-details details">
<div class="detail-content">
<div id="img">
<!-- Loop (for yin would be image01, and image03) -->
</div>
<div id="details">
<!-- Loop (for yin would be 'aaaaaa','bbbbbb') -->
</div>
</div>
</div>
</div>
</div>
</div>
I would take the click function out to a named function though and just pass in the arrays.