Random posts in javascript or php - javascript

I have 30 divs with different images and links and wanted to get them to be displayed in 10 different divs randomly.
Example: http://imgur.com/Ar1gdzL (it's an animated gif)
Something like a "random related posts" that we use in wordpress, but my page is not in wordpress. It's just a simple website in php.
 
the div would be so
Link
Link
Link
etc
etc
etc
How to do this in javascript or php?

Create 10 divs with those positions (empty divs)
Create a string array with the 10 (or more) html content that will fill the divs
Shuffle the array as stated here
Pass by the array and modify the innerHtml of the 10 divs one by one (Only first 10 elements since only 10 divs)

You can use different ways, depending on your needs. When using MySQL you can use a query like:
SELECT images, link FROM tablename WHERE ...... ORDER BY RAND()
Or you can use shuffle on an array.
$array = array ( 'image1', 'image2' );
shuffle ( $array );
// Display divs

<div class="divPool">content 1</div>
<div class="divPool">content 2</div>
<div class="divPool">content 3</div>
etc... to 30 divs
<div class="destination">destination 1</div>
<div class="destination">destination 2</div>
<div class="destination">destination 3</div>
etc. to 10 divs,
then in JavaScript:
//make arrays of the html elements in each class:
var arrayOfContent=document.getElementsByClassName("divPool");
var arrayOfDestinations=document.getElementsByClassName("destination");
for (var i=0; i<10: i++){//for each of the 10 destination divs
//select a random number from 0 to 29
var random=Math.floor(Math.random() * 30);
arrayOfDestinations[i].innerHTML=arrayOfContent[random].innerHTML
}
Also, in css you can make the divPool class invisible like this:
.divPool{display:none}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
for(i=1;i<=10;i++){
var id = Math.floor(Math.random() * 30) + 1;
$("#display_"+id).show();
}
});
</script>
<div id="display_1" style="display:none;">1</div>
<div id="display_2" style="display:none;">2</div>
<div id="display_3" style="display:none;">3</div>
<div id="display_4" style="display:none;">4</div>
<div id="display_5" style="display:none;">5</div>
<div id="display_6" style="display:none;">6</div>
<div id="display_7" style="display:none;">7</div>
<div id="display_8" style="display:none;">8</div>
<div id="display_9" style="display:none;">9</div>
<div id="display_10" style="display:none;">10</div>
<div id="display_11" style="display:none;">11</div>
<div id="display_12" style="display:none;">12</div>
<div id="display_13" style="display:none;">13</div>
<div id="display_14" style="display:none;">14</div>
<div id="display_15" style="display:none;">15</div>
<div id="display_16" style="display:none;">16</div>
<div id="display_17" style="display:none;">17</div>
<div id="display_18" style="display:none;">18</div>
<div id="display_19" style="display:none;">19</div>
<div id="display_20" style="display:none;">20</div>
<div id="display_21" style="display:none;">21</div>
<div id="display_22" style="display:none;">22</div>
<div id="display_23" style="display:none;">23</div>
<div id="display_24" style="display:none;">24</div>
<div id="display_25" style="display:none;">25</div>
<div id="display_26" style="display:none;">26</div>
<div id="display_27" style="display:none;">27</div>
<div id="display_28" style="display:none;">28</div>
<div id="display_29" style="display:none;">29</div>
<div id="display_30" style="display:none;">30</div>
`

Related

Reorder divs in javascript without jquery

lets say I have html:
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
how would I in javascript and not jquery reorder these divs to:
<div id="1">1</div>
<div id="3">3</div>
<div id="2">2</div>
You can use display:flex and the order css (I had to add a letter before the number for your id as SO didn't seem to like it for the css)
.container {display:flex; flex-direction:column}
#s1 {order:1;}
#s2 {order:3;}
#s3 {order:2;}
<div class="container">
<div id="s1">1</div>
<div id="s2">2</div>
<div id="s3">3</div>
</div>
More information about order
More information about flex
Update
Sorry read the question wrong - thought you wanted to do it without js
var div = document.getElementById('3')
div.parentNode.insertBefore(div, document.getElementById('2'))
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
The solution given by the duplicate questions are incorrect because they make the assumption that the elements are next to each other. But even in this simple example, there is a text node containing white-space between the elements.
Given that the two elements are not nested, you can use this to swap two elements:
function swapElements (first, second) {
var tmpNode = document.createElement('div');
tmpNode.setAttribute('id', '_tmp');
var firstParent = first.parentNode;
firstParent.insertBefore(tmpNode, first);
second.parentNode.insertBefore(second, first);
firstParent.insertBefore(second, tmpNode);
firstParent.removeChild(tmpNode);
}
Use it like:
var first = document.querySelector('#1');
var second = document.querySelector('#2');
swapElements(first, second);

combine html paragraphs using javascript

I'm currently struggling on a very simple javascript task, but I'm new to it, so its confusing me a lot.
e.g. html
<div class="item">
<div class="title">Item 1 Title</div>
<div class="description-1">lorum</div>
<div class="description-2">ipsum</div>
<div class="description-combined"></div>
</div>
So I need to combine paragraphs 1 & 2, and replace the empty info in paragraph 3. I don't use jQuery yet, so my research has caused struggle because of this.... i currently have:
var p1 = getElementsByClassName ('description-1').innerHTML;
var p2 = getElementsByClassName ('description-2').innerHTML;
var p3 = p1 + P2
document.getElementsByClassName ('description-combined').innerHTML = p3
I did have p3 to have p1.concat(p2) but that didn't work. I'm using it as an external file, so i may be missing out on putting something in my HTML file too.
The edit changes the question.
What I'd probably do is loop through the .item elements, combining the descriptions within.
document.getElementsByClassName is a property of document, not a freestanding function, and it returns a list of matching elements. It's also not as widely supported as document.querySelector and document.querySelectorAll, so I'd probably use those; for what we're talking about, we'll also want Element#querySelector.
// Get a list of the items and loop through it
Array.prototype.forEach.call(document.querySelectorAll(".item"), function(item) {
// Get the two description divs, and the combined, that
// are *within* this item
var d1 = item.querySelector(".description-1");
var d2 = item.querySelector(".description-2");
var c = item.querySelector(".description-combined");
// Set the combined text (this assumes we have them all)
c.innerHTML = d1.innerHTML + d2.innerHTML;
});
.description-combined {
color: green;
}
<div class="item">
<div class="title">Item 1 Title</div>
<div class="description-1">One description 1</div>
<div class="description-2">One description 2</div>
<div class="description-combined"></div>
</div>
<div class="item">
<div class="title">Item 2 Title</div>
<div class="description-1">2 description 1</div>
<div class="description-2">2 description 2</div>
<div class="description-combined"></div>
</div>
<div class="item">
<div class="title">Item 3 Title</div>
<div class="description-1">3 description 1</div>
<div class="description-2">3 description 2</div>
<div class="description-combined"></div>
</div>
The Array.prototype.forEach.call(list, function() { ... }); thing is a way to loop through anything that's like an array, but isn't an array. It's explained more in this other answer, which also has several alternatives.

jQuery Insert closing div tag and opeing div tag after count

I am trying to get jquery to close a div and inset an opening div with a class after x amount of items.
Here is what I have tried:
$(this).after('</div> <div class=\"bar">Bar');
it outputs:
<div class="bar">Bar</div>
What I need is:
<div class="item2">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
<div class="bar">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
<div class="bar">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
<div class="bar">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
http://jsfiddle.net/yoderman94/JEtj2/
You can't add half a tag. I think what you're trying to do is wrap the elements. Your fiddle is pretty messy, but here's a simple example of how you can do that:
http://jsfiddle.net/9Q62H/
while($('#wrapper > a:lt(2)').wrapAll('<div class="bar">bar</div>').length) { }
Which turns this:
<div id="wrapper">
1
1
1
1
1
1
1
1
</div>
into this:
<div id="wrapper">
<div class="bar">bar
1
1
</div>
<div class="bar">bar
1
1
</div>
<div class="bar">bar
1
1
</div>
<div class="bar">bar
1
1
</div>
</div>
You can't manipulate the DOM that way, with or without jQuery. To accomplish the same thing, insert a new div after the current div's parent, and then move all of the current div's following siblings to the new div:
var bar = $("<div>").addClass("bar").text("Bar");
bar.insertAfter($(this).parent());
bar.append($(this).nextAll());
Edit: To preserve text nodes, including the whitespace between your links, it's not quite as simple as $(this).nextAll(), sadly. You need to use .contents() to select the text nodes, then slice at the index of this:
var contents = $(this).parent().contents();
var bar = $("<div>").addClass("bar").text("Bar");
bar.insertAfter($(this).parent());
bar.append(contents.slice(contents.index(this) + 1));
http://jsfiddle.net/JEtj2/6/
I'm going to recommend a different approach here. When you call .after() you need to be giving it a complete open and close tag. You cannot open a tag then close it later like you are trying to above.
My advice would be to try and take an approach like the following, so you can pass a complete open and close tag to .after()
var theDiv = "<div class='bar'>";
for(var i = 0; i < 2; i++) {
theDiv += '<div class="CountThese2"> Count Me </div>';
}
theDiv += "</div>";
$('#thing').after(theDiv);
See how I constructed the whole div including contents before calling .after() ?

Append a div to a new div

i am using IPB and i am going to put each category into a new tab the category div is something like this:
<div id='category_100'>
<div id='category_104'>
<div id='category_102'>
<div id='category_101'>
and my tabs content is like this:
<div class="content">
<div id="content-1" class="content-1">
</div>
</div>
and the categories divs is already showing but i want it to be moved to the content-1 div without duplicate so i want it to move from its div to this div with jjava script how?
<script>
document.getElementById('content-1').appendChild(
document.getElementById('category_100')
);
</script>
this worked for me but how can i add more than id to category_100
i want it to be like this in one script code so i would not repeart the scrip code four times:
<div class="content">
<div id="content-1" class="content-1">
<div id='category_100'>
<div id='category_104'>
<div id='category_102'>
<div id='category_101'>
</div>
</div>
using my two lines the suggested things here is not working!
Try this code :
$('div[id^="category_"]').appendTo('#content-1')
Have a look to this fiddle : http://jsfiddle.net/lulu3030/sjEPx/2/
"using my two lines the suggested things here is not working!"
You just get a single element with an ID and trying to append it...
Live Demo
If you want to append multiple elements, there are many ways...
Wrap those elements and then append...
<div id="categories">
<div id='category_100'></div>
<div id='category_104'></div>
<!-- etc. -->
</div>
document.getElementById('content-1').appendChild(document.getElementById('categories'));
or add same class to all elements that you want to append...
<div id='category_100' class="myClass"></div>
<div id='category_104' class="myClass"></div>
[].forEach.call(document.getElementsByClassName("myClass"), function (value, index, array) {
document.getElementById("content-1").appendChild(value);
});
or get elements with query selector that match some pattern...
[].forEach.call(document.querySelectorAll("div[id^='category_']"), function (value, index, array) {
document.getElementById("content-1").appendChild(value);
});
and etc.

How can I hide elements in my list and add a 'show more' feature?

I'm using javascript to build a list of results. I have a for-loop that iterates over some data and creates a mydata div, and adds that to the results div. Let's pretend it looks something like this:
<div id="results">
<div class="mydata">data 1</div>
<div class="mydata">data 2</div>
...
<div class="mydata">data 20</div>
</div>
What I want to do is only display 5 results at a time, and should the user wish to see more, they can click a show next 5 or show more button (or something similar). Any ideas?
Just to clarify, every time the user clicks "show more" I want to 'unhide' the next 5 elements, not ALL the remaining elements. So each click reveals more elements until all are displayed.
You can use the gt() and lt() selectors along with :visible pretty well here.
The following will show the next 5 results on clicking and removes the link once all items are visible.
$('.mydata:gt(4)').hide().last().after(
$('<a />').attr('href','#').text('Show more').click(function(){
var a = this;
$('.mydata:not(:visible):lt(5)').fadeIn(function(){
if ($('.mydata:not(:visible)').length == 0) $(a).remove();
}); return false;
})
);
working example: http://jsfiddle.net/niklasvh/nTv7D/
Regardless of what other people are suggesting here, I would not hide the elements using CSS, but do it in JS instead, because if a user has JS disabled and you hide the elements using CSS, he won't get them visible. However, if he has JS disabled, they will never get hidden, nor will that button appear etc, so it has a full noscript fallback in place + search engines don't like hidden content (but they won't know its hidden if you do it on DOM load).
My solution is here: jsFiddle.
You can put this link somewhere:
show more
and use the following code:
var limit = 5;
var per_page = 5;
jQuery('#results > div.mydata:gt('+(limit-1)+')').hide();
if (jQuery('#results > div.mydata').length <= limit) {
jQuery('#results-show-more').hide();
};
jQuery('#results-show-more').bind('click', function(event){
event.preventDefault();
limit += per_page;
jQuery('#results > div.mydata:lt('+(limit)+')').show();
if (jQuery('#results > div.mydata').length <= limit) {
jQuery(this).hide();
}
});
where limit is your current number of results displayed and per_page is number of results shown with each click on "show more". The link disappears if all the results are displayed. See how it works on jsFiddle.
You can create a CSS class like:
.hiddenData { display: none }
and attach it to any quantity of divs that exceeds 5.
After that make handlers for adding/deleting this class from the needed quantity of divs.
jQuery for class removing:
$(".hiddenData").removeClass("hiddenData")
Create a class with something like:
.hidden_class{
display: none;
}
Add this class to all the mydata div's that you dont want seen.
when the user click the button, remove it from the next 5 div's.
repeat everytime the user clicks the "read more" button
This should work...Let me know how it goes
<script type="text/javascript">
function ShowHide(id) { $("#" + id).toggle(); }
</script>
<div id="results">
<div class="mydata">data 1</div>
<div class="mydata">data 2</div>
<div class="mydata">data 3</div>
<div class="mydata">data 4</div>
<div class="mydata">data 5</div>
<div style="clear:both" onclick="ShowHide('grp6')">More</div>
<div id="grp6" style="display:none">
<div class="mydata">data 6</div>
<div class="mydata">data 7</div>
<div class="mydata">data 8</div>
<div class="mydata">data 9</div>
<div class="mydata">data 10</div>
</div>
<div style="clear:both" onclick="ShowHide('grp11')">More</div>
<div id="grp11" style="display:none">
<div class="mydata">data 11</div>
<div class="mydata">data 12</div>
<div class="mydata">data 13</div>
<div class="mydata">data 14</div>
<div class="mydata">data 15</div>
</div>
</div>
In your forloop, you also have to add these divs hidden container
<div style="clear:both" onclick="ShowHide('grp6')">More</div>
<div id="grp6" style="display:none">
You get the idea.
Here you have:
<style>
/*This hides all items initially*/
.mydata{
display: none;
}
</style>
Now the script
<script>
var currentPage = 1; //Global var that stores the current page
var itemsPerPage = 5;
//This function shows a specific 'page'
function showPage(page){
$("#results .mydata").each(function(i, elem){
if(i >= (page-1)*itemsPerPage && i < page*itemsPerPage) //If item is in page, show it
$(this).show();
else
$(this).hide();
});
$("#currentPage").text(currentPage);
}
$(document).ready(function(){
showPage(currentPage);
$("#next").click(function(){
showPage(++currentPage);
});
$("#prev").click(function(){
showPage(--currentPage);
});
});
</script>
And a sample html:
<div id="results">
<div class="mydata">data 1</div>
<div class="mydata">data 2</div>
<div class="mydata">data 3</div>
<div class="mydata">data 4</div>
<div class="mydata">data 5</div>
<div class="mydata">data 6</div>
<div class="mydata">data 7</div>
<div class="mydata">data 8</div>
<div class="mydata">data 9</div>
<div class="mydata">data 10</div>
<div class="mydata">data 11</div>
<div class="mydata">data 12</div>
</div>
Previous
<span id="currentPage"></span>
Next
The only thing remaining is to validate fot not going to a page lower than 1 and higher than the total. But that will be easy.
EDIT: Here you have it running: http://jsfiddle.net/U8Q4Z/
Hope this helps. Cheers.

Categories

Resources