Replacing multiple div content with other content and being able to cycle - javascript

Currently I have the following:
<div class="ArrowLeft"></div>
<div class="ArrowRight"></div>
<div class="ReviewComment">
<p>“Thank you for making selling our car so painless.”</p>
</div>
<div class="ReviewName">
</div>
</div>
I've been looking at different ways to get it to work so that when click one of the "Arrow" buttons, it replaces the content in "ReviewComment". However so far i've only managed to get it to replace the content going one way. So for example when it gets to the 5th div's content, it won't then click back to the first one?
I've tried multiple different ways of doing this but I can't seem to get it to cycle through as I would like.
I also can't seem to get it to replace the content of ReviewName at the same time as ReviewComment.

Keep track of what comment you're on, and how many comments there are. If total comments == current comment, go back to the first one. Ex code:
var comments = ['comment 1', 'comment 2', 'comment 3', 'comment 4', 'comment 5'];
var currentComment = 0;
var totalComments = comments.length - 1;
$('.arrowRight').click(function(){
currentComment++;
if(currentComment > totalComments){
// past last comment, load first
$('.comments .comment').html(comments[0]);
currentComment = 0;
}else{
$('.comments .comment').html(comments[currentComment]);
}
console.log(currentComment);
})
$('.arrowLeft').click(function(){
currentComment--;
if(currentComment < 0){
// past first comment, load last
$('.comments .comment').html(comments[totalComments]);
currentComment = totalComments;
}else{
$('.comments .comment').html(comments[currentComment]);
}
console.log(currentComment);
})
T̶h̶i̶s̶ ̶c̶o̶d̶e̶ ̶a̶s̶ ̶i̶s̶ ̶w̶i̶l̶l̶ ̶n̶o̶t̶ ̶w̶o̶r̶k̶ I don't know how you're fetching your comments. But you can transplant the logic from the example in to your own code. Hopefully this gets you on your way.
I'll try and edit with a js fiddle shortly.
UPDATE
Working fiddle here: https://jsfiddle.net/mpr9j6sd/

Related

How do i call something out from my LocalStorage and make the thing dynamic

I am currently trying to stimulate a forum. And what i have done so far, is when a user asked a question
The topic and questions will be saved into an object and pushed into an array
On the main page, all the objects in the array will be displayed
I will be able to click on each of the displayed links.
But here comes the tricky part. How do i use one same HTML and change the code in it dynamically.
I know i call use a array[0].Question to change the content of the INNERHTML code. But i do not know how to make a specific array[Number] come out.
For example. If i have a array of length 0 - 4! And i want to call the array[0] when i clicked the first link. Followed by array[1] when i clicked the second link! How do i do it!
Another solution i found is the use of URL hash. However in order to use URL hash, i have to make 5 amount of pages if i want to make all my array object dynamic right?
Hopefully you guys understand what i mean!
From what I've gathered, you have an array of questions like
var questions = [{
title: 'Question 1',
description: 'something about Question 1'
}, {
title: 'Question 2',
description: 'something about Question 2'
}]
And you want to be able to show the description for each question without actually navigating to a new page. This is possible with plain javascript (cleaner with jQuery).
Here is a general plain js approach you can build on:
var questions = [{
title: 'Question 1',
description: 'something about Question 1'
}, {
title: 'Question 2',
description: 'something about Question 2'
}]
var questionContainer = document.getElementById('questions');
var descriptionContainer = document.getElementById('description');
var contentContainer = document.getElementById('content');
var backBtn = document.getElementById('back-btn');
questions.forEach(function(question) {
var q = document.createElement('div');
q.innerText = question.title;
q.className = 'question';
q.addEventListener('click', function() {
contentContainer.innerText = question.description;
descriptionContainer.style.display = 'block';
questionContainer.style.display = 'none';
})
questionContainer.appendChild(q);
})
backBtn.addEventListener('click', function() {
descriptionContainer.style.display = 'none';
questionContainer.style.display = 'block';
})
.question:hover,
#back-btn:hover {
color: blue;
cursor: pointer;
}
<div id="questions"></div>
<div id="description" style="display: none;">
<div id="back-btn">Back</div>
<div id="content"></div>
</div>
Please note This is fine for playing around, or a personal project. However, the end result is still "static" because you have a static array of questions you are storing on the front end. If you want this to be truly dynamic, you will have to store questions and all relevant details in some kind of database.

dynamically insert div after row containing floating divs jquery [duplicate]

I have a number of divs floating in several rows. The divs contain text-previews and a link to slide down the full content (see http://jsfiddle.net/yDcKu/ for an example).
What happens now: When you slide down the content-div it opens right after the connected preview.
What I want to happen: Open the content-div after the last div in the row.
I assume the could be done by:
1. find out which div is the last one in the row of the activated preview,
2. add an id to this div and
3. append the content-div to this div.
I have a solution for steps 2 und 3 using jQuery but no guess how to do the first step.
I can manage to get the document width and the x- and y-value of each div but I have no idea how to find out which div has the highest x- as well the highest y-value and as well is in the row of the activated preview-div.
Any idea anyone? Thanks
Here is an example that does what you want. I simplified your code, so you don't have to manually ID every entry and preview.
http://jsfiddle.net/jqmPc/1/
It's a little complicated. Let me know if you have questions.
Basically, when the window is resized, the script goes through and finds the first preview in each row by finding the preview with the same left offset as the very first one. It then adds a class last to the entry before (previous row) and class first to this preview. I do css clear: left on both of these so that everything wraps normally when the entries open.
I made your code generic, without IDs:
<div class="preview">
<p>Some preview text <a class="trigger" href="#">…</a></p>
</div>
<div class="entry">
<div class="close_button">
<a class="close" href="#">×</a>
</div>
<p>Some content text.</p>
</div>
This makes you not have to write the same code over and over.
The open/close script:
$('.trigger').click(function() {
$('.openEntry').slideUp(800); // Close the open entry
var preview = $(this).closest('.preview'); // Grab the parent of the link
// Now, clone the entry and stick it after the "last" item on this row:
preview.next('.entry').clone().addClass('openEntry').insertAfter(preview.nextAll('.last:first')).slideDown(800);
});
// Use "on()" here, because the "openEntry" is dynamically added
// (and it's good practice anyway)
$('body').on('click', '.close', function() {
// Close and remove the cloned entry
$('.openEntry').slideUp(800).remove();
});
This could be simplified a bit I'm sure, especially if you were willing to reformat your html a little more, by putting the entry inside of the preview element (but still hidden). Here is a slightly simpler version, with the html rearranged:
http://jsfiddle.net/jqmPc/2/
(I also color the first and last element on the line so you can see what is going on)
You could just get the last div in the array after calling getElementsByTagName.
var divArray = wrapperDiv.getElementsByTagName("div");
if(divArray.length > 0)
var lastDiv = divArray[divArray.length-1];
else
console.log("Empty!");
i am not able to correctly understand your question, but if you want to find out last div element in the document then you can do something like this
$("div:last")
so this will give you last div of the document
Reference:
http://api.jquery.com/last-selector/
$([1,2]).each(function(idx,el) {
$("#entry" + el).hide().insertAfter("div.entry:last");
$("#trigger" + el).click(function() {
$("#entry" + el).slideDown('800');
});
$("#close" + el).click(function() {
$("#entry" + el).slideUp('800');
});
});​
http://jsfiddle.net/yDcKu/11/
I got same problem as yours, and I have been redirected to this question. But I think the answer is too complicated to my need. So I made my own way. Supposedly, you get your div list from a JSON, you can do this:
product[0] = {id: "name1", text: "text1"}
product[1] = {id: "name2", text: "text2"}
product[2] = {id: "name3", text: "text3"}
private getLastElement(id, products) {
const getTop = (id) => $("#" + id).position().top;
let itemPos = getTop(id);
let itemIndex = products.map(x => x.id).indexOf(id);
let lastID = itemIndex;
while (lastID < products.length - 1) {
if (getTop(products[lastID + 1].id) > itemPos) break;
lastID++;
}
return products[lastID].id;
}
But you can also find out by gathering all id inside your wrapper.
It works by scanning next id's row position, and return the last id of the same row.
I was looking for the same but on a single element to add style on first and last elements. #Jeff B answer helped me so alter and use it for me on one element. So the search phrase 'Get the last div in a row of floating divs' and someone looking for the same, this code may helpful:
Fiddle: https://jsfiddle.net/kunjsharma/qze8n97x/2/
JS:
$(function() {
$(window).on('resize', function() {
var startPosX = $('.preview:first').position().left;
$('.preview').removeClass("first last");
$('.preview').each(function() {
if ($(this).position().left == startPosX) {
$(this).addClass("first");
$(this).prevAll('.preview:first').addClass("last");
}
});
$('.preview:last').addClass("last");
});
$(window).trigger('resize');
});
CSS:
.preview {
float: left;
}
HTML:
<div class="preview">
<p>Some preview text</p>
</div>
<div class="preview">
<p>Some preview text</p>
</div>
<div class="preview">
<p>Some preview text</p>
</div>
<div class="preview">
<p>Some preview text</p>
</div>

jQuery change ID of all DIVs with ID < than $(this).attr("id");

I have an sortable grid of elements, that updates its value to DB after user moves the element. The problem is, I don't know how to update the id of all previous elements to a new one without reloading the page.
In PHP, I would do something like this (code from FAQ of one of my older pages), but I can't use PHP (it has to happen without any page reloading, right after user places element he moved):
if ($old_order > $order){
$result = dbquery("UPDATE faq SET orders=orders+1 WHERE orders>='$order' AND orders<='$old_order'");
}else{
$result = dbquery("UPDATE faq SET orders=orders-1 WHERE orders>='$old_order' AND orders<='$order'");
}
I would like to do that with jQuery, basically I have 7 elements with id from 0 to 6 and every time user changes the position, I serialize it and send it with ajax to an php code that saves it.
What it does now:
Move elemtent 1 to position 4.
Saves and works.
Move element 3 to position 2
Moves element 1 from position 4 back to his old one, as the ID of it
is still 1 and not 4.
What I want to do:
Move element 1 to position 4
Change ID of element 1 from 1 to 4
Change ID of element 2, 3 and 4 by -1 to id 1, 2 and 3
I hope somebody understands me and can help me.
jQuery code I actauly use:
$(".content-page").sortable({
start: function(e,ui){
ui.placeholder.height($(".sorted-icons").outerHeight(true));
ui.placeholder.width($(".sorted-icons").outerWidth(true));
},
placeholder: 'placeholder',
items: '.sorted-icons:not(.new_icon)',
update: function(e,ui) {
var order = $(this).sortable("serialize") + '&order=icons' + '&content_id=' + $(this).attr("data-shortcut-id");
console.log(order);
$.post("page_ajax.php", order).done(function(data){
console.log(data);
}).fail(function(data){
console.log(data);
});
}
}).disableSelection();
Html code basically looks like this with content inside of that div thats irelevant:
echo "<div class='sorted-icons' id='icon_$id'>";
If you have any questions, just comment and Ill try to answer them and update the queston.
Fixed jQuery:
var i = 0;
$(this).children('.sorted-icons').each(function(){
$(this).attr('id', 'icon_' + i);
i++;
});
Still have problem with PHP part tho. Its saving them in weird orders.
Ok, so I had one little bug in my PHP code, but I managed to fix the jQuery with really simple pice of code:
$(".content-page").sortable({
start: function(e,ui){
ui.placeholder.height($(".sorted-icons").outerHeight(true));
ui.placeholder.width($(".sorted-icons").outerWidth(true));
},
placeholder: 'placeholder',
items: '.sorted-icons:not(.new_icon)',
update: function(e,ui) {
var order = $(this).sortable("serialize") + '&order=icons' + '&content_id=' + $(this).attr("data-shortcut-id");
console.log(order);
$.post("page_ajax.php", order);
// THIS PART //
var i = 0;
$(this).children('.sorted-icons').each(function(){
$(this).attr('id', 'icon_' + i);
i++;
});
// THIS PART //
}
}).disableSelection();
Hopefully might help somebody else.

4 toggle buttons speak javascript to each other but none of them are good listeners- the sequel: stupidity strikes back

This is the sequel to this thread:
4 toggle buttons speak javascript to each other but none of them are good listeners
Our heros have overcome the ridiculous amount of nonsense originally presented in the fiddle http://jsfiddle.net/EjW7A/8/ (no longer available) when #nbrooks -reinvigorated by the forces of good- conquered all of the stupidly placed arrays, functions and the mammoth amount of redundant content with his solution:
http://jsfiddle.net/EjW7A/24/
We rejoin Luhring after 8 hours of poking, prodding, red bull drinking, concrete wall head-bashing at the final step of solving the epic problem of doom- implementation:
The new fiddle:
http://jsfiddle.net/Luhring/EjW7A/38/
Problem:
How can I insert the content dynamically- allowing each button to toggle it's own content while making sure the other buttons are toggled off and their content hidden? ex, if button 1 is toggled on (it is animated as if it were a 'real' pressed button), button 1s content is displayed in a gallery where the contents can be clicked to display a lightbox. when button 2 is clicked should toggle button 1 off and replace button 1's contents with its own.
New Working Demo
Anything invoking jQuery on DOM elements must be wrapped within the DOM ready function to work correctly (this is why your $('a').click() was failing. Also, normally if you see yourself creating multiple arrays that you never end up using, and still end up referencing each element directly, you're making a lot of wasted effort. I cleaned your code up a bit - take a look:
jQuery(document).ready(function($) {
//variable declaration section.
var contentArray = ['albumArt', 'logoDesign', 'UX', 'other'],
content = {}, newClassName, $selectedArray, i;
for ( i = 0; i < contentArray.length; i++) {
var className = contentArray[i];
content[className] = $('.' + className);
}
//prevent links that are clicked from going anywhere
$("a").click(function(e) {
e.preventDefault();
});
$('.workTypes').click(function() {
if ($(this).is('#centeringDiv a')) return;
$(this).toggleClass('workTypesSelected');
$('.workTypesSelected').not(this).removeClass('workTypesSelected');
$selectedArray = content[$('.workTypesSelected').attr('id')];
$('#galleryDiv').empty();
if ( $selectedArray ) {
// note creates #largeGallery elements dynamically
for ( i = 0; i < $selectedArray.length; i++ ) {
var $selected = $selectedArray.eq(i);
$('<a>').attr({
href: $selected.attr('href'),
title: $selected.attr('title'),
class: "lb_gal"
}).append(
$('<img>').attr({
id: "largeGallery"+i,
src: $selected.attr('href'),
class: "gallery cf"
}).rlightbox()
)
.appendTo('#galleryDiv')
.rlightbox();
}
}
}); // end click handler
}); //end the document ready jquery function​

Get the last div in a row of floating divs

I have a number of divs floating in several rows. The divs contain text-previews and a link to slide down the full content (see http://jsfiddle.net/yDcKu/ for an example).
What happens now: When you slide down the content-div it opens right after the connected preview.
What I want to happen: Open the content-div after the last div in the row.
I assume the could be done by:
1. find out which div is the last one in the row of the activated preview,
2. add an id to this div and
3. append the content-div to this div.
I have a solution for steps 2 und 3 using jQuery but no guess how to do the first step.
I can manage to get the document width and the x- and y-value of each div but I have no idea how to find out which div has the highest x- as well the highest y-value and as well is in the row of the activated preview-div.
Any idea anyone? Thanks
Here is an example that does what you want. I simplified your code, so you don't have to manually ID every entry and preview.
http://jsfiddle.net/jqmPc/1/
It's a little complicated. Let me know if you have questions.
Basically, when the window is resized, the script goes through and finds the first preview in each row by finding the preview with the same left offset as the very first one. It then adds a class last to the entry before (previous row) and class first to this preview. I do css clear: left on both of these so that everything wraps normally when the entries open.
I made your code generic, without IDs:
<div class="preview">
<p>Some preview text <a class="trigger" href="#">…</a></p>
</div>
<div class="entry">
<div class="close_button">
<a class="close" href="#">×</a>
</div>
<p>Some content text.</p>
</div>
This makes you not have to write the same code over and over.
The open/close script:
$('.trigger').click(function() {
$('.openEntry').slideUp(800); // Close the open entry
var preview = $(this).closest('.preview'); // Grab the parent of the link
// Now, clone the entry and stick it after the "last" item on this row:
preview.next('.entry').clone().addClass('openEntry').insertAfter(preview.nextAll('.last:first')).slideDown(800);
});
// Use "on()" here, because the "openEntry" is dynamically added
// (and it's good practice anyway)
$('body').on('click', '.close', function() {
// Close and remove the cloned entry
$('.openEntry').slideUp(800).remove();
});
This could be simplified a bit I'm sure, especially if you were willing to reformat your html a little more, by putting the entry inside of the preview element (but still hidden). Here is a slightly simpler version, with the html rearranged:
http://jsfiddle.net/jqmPc/2/
(I also color the first and last element on the line so you can see what is going on)
You could just get the last div in the array after calling getElementsByTagName.
var divArray = wrapperDiv.getElementsByTagName("div");
if(divArray.length > 0)
var lastDiv = divArray[divArray.length-1];
else
console.log("Empty!");
i am not able to correctly understand your question, but if you want to find out last div element in the document then you can do something like this
$("div:last")
so this will give you last div of the document
Reference:
http://api.jquery.com/last-selector/
$([1,2]).each(function(idx,el) {
$("#entry" + el).hide().insertAfter("div.entry:last");
$("#trigger" + el).click(function() {
$("#entry" + el).slideDown('800');
});
$("#close" + el).click(function() {
$("#entry" + el).slideUp('800');
});
});​
http://jsfiddle.net/yDcKu/11/
I got same problem as yours, and I have been redirected to this question. But I think the answer is too complicated to my need. So I made my own way. Supposedly, you get your div list from a JSON, you can do this:
product[0] = {id: "name1", text: "text1"}
product[1] = {id: "name2", text: "text2"}
product[2] = {id: "name3", text: "text3"}
private getLastElement(id, products) {
const getTop = (id) => $("#" + id).position().top;
let itemPos = getTop(id);
let itemIndex = products.map(x => x.id).indexOf(id);
let lastID = itemIndex;
while (lastID < products.length - 1) {
if (getTop(products[lastID + 1].id) > itemPos) break;
lastID++;
}
return products[lastID].id;
}
But you can also find out by gathering all id inside your wrapper.
It works by scanning next id's row position, and return the last id of the same row.
I was looking for the same but on a single element to add style on first and last elements. #Jeff B answer helped me so alter and use it for me on one element. So the search phrase 'Get the last div in a row of floating divs' and someone looking for the same, this code may helpful:
Fiddle: https://jsfiddle.net/kunjsharma/qze8n97x/2/
JS:
$(function() {
$(window).on('resize', function() {
var startPosX = $('.preview:first').position().left;
$('.preview').removeClass("first last");
$('.preview').each(function() {
if ($(this).position().left == startPosX) {
$(this).addClass("first");
$(this).prevAll('.preview:first').addClass("last");
}
});
$('.preview:last').addClass("last");
});
$(window).trigger('resize');
});
CSS:
.preview {
float: left;
}
HTML:
<div class="preview">
<p>Some preview text</p>
</div>
<div class="preview">
<p>Some preview text</p>
</div>
<div class="preview">
<p>Some preview text</p>
</div>
<div class="preview">
<p>Some preview text</p>
</div>

Categories

Resources