Alright. This might sound a little bit complicated. I've got a script which fetches thumbnails from a JSON. It fetches 9 thumbnails and onclick of the #load it fetches 9 more. How can I set the Load more button underneath the thumbnails and how to make it stick to the bottom of them each time you click it? ( I do not want it like it's now, on the side, but right in the middle and underneath them ).
+BONUS question: How can I fixate the thumbnails so they always show up 3 in a row. Since now, when I resize the window they change ( as you can see in the fiddle, there's only 2 per row now ).
jsfiddle.net/z6ge55ky/
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="twitch">
<script src="js/main.js"></script>
<div id="load">
<img class="hvr-pulse" src="http://i.imgur.com/KHIYHFz.png?1">
</div>
</div>
$(function() {
var i=0;
var twitchApi = "https://api.twitch.tv/kraken/streams";
var twitchData;
$.getJSON(twitchApi, function(json) {
twitchData = json.streams;
setData()
});
function setData(){
var j = twitchData.length > (i + 9) ? (i + 9) : twitchData.length;
for (; i < j; i++) {
var streamGame = twitchData[i].game;
var streamThumb = twitchData[i].preview.medium;
var streamVideo = twitchData[i].channel.name;
var img = $('<img style="width: 250px; height: 250px;" src="' + streamThumb + '"/>')
$('#twitch').append(img);
img.click(function(){
$('#twitch iframe').remove()
$('#twitchframe').append( '<iframe frameborder="0" style="overflow:hidden; margin-left: 25px; width:400px; height:250px; position: fixed; top: 0; margin-top: 23.55%;" src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
});
}
}
$('#load').click(function() {
setData();
});
});
#twitch {
width: 60%;
position: absolute;
left: 20%;
text-align: center;
}
#twitch img {
border: 5px solid rgba(0,0,0,0);
margin: 0 auto;
cursor: pointer;
}
#load {
bottom: 0;
position: absolute;
}
You have declared the width for #twitch 60% remove that and for #load use top:100%
DEMO on jsfiddle
Related
I have a function which counts the number of line breaks in a div, depending on the width of the window. While the functions works fine when placed in the $(window).on('resize') function, it does not work when put in $(document).ready() function. I want it to work right on page load, and also window resize, how do I support both?
JSFiddle
Javascript/jQuery:
// functions called in both document.ready() and window.resize
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.line').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
You'll see at the start of the page, it incorrectly shows 17 lines, and then once you resize it will show the correct amount.
The issue lies in the first line of getLineCount(). Originally you had
var lineWidth = $('.line').width();
but no elements with the class "line" exist yet on your page (since they get added in your postItems() method. I changed it to
var lineWidth = $(".container").width();
instead, and now your code should be working. Snippet posted below:
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.container').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
body {
text-align:center;
}
.answer {
position: fixed;
left: 0;
bottom: 0;
}
.container {
position: relative;
width: 50%;
margin: 0 auto;
border: 1px solid #e8e8e8;
display: inline-block;
}
.item {
height: 50px;
padding:0 10px;
background-color: #aef2bd;
float: left;
opacity:0.2;
white-space: nowrap;
}
.line-wrap {
position: absolute;
border: 1px solid red;
width: 100%;
height: 100%;
top:0; left: 0;
}
.line {
height: 50px;
width: 100%;
background-color: blue;
opacity:0.5;
color: white;
transition: all 0.5s ease;
}
.line:hover {
background-color: yellow;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="item-wrap">
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
</div>
<div class="line-wrap">
</div>
</div>
<h1 class="answer"></h1>
I have a website, where I want to change between images in the background very smoothly. This is my actual javaScript-code for it:
var bg=[
'images/best.jpg',
'images/61182.jpg',
'images/bg.jpg'
];
$('._container-1').css('background-image','url('+bg[2]+')');
window.setInterval(
function(){
img=bg.shift();bg.push(img);
document.getElementsByClassName('_container-1')[0].style.backgroundImage='url('+img+')';
},
10000
);
Now, I want to change the images very slowly. I have tried a lot with jQuery-fadeIn/fadeOut-methods like this:
window.setInterval(
function(){
img=bg.shift();
bg.push(img);
$('._container-1').fadeOut(600, function() {
$('._container-1').css('background-image','url('+img+')');
$('._container-1').fadeIn(600);
});
},
17000
);
The problem is, that there are buttons and text in the container and they changes with the images. I want that the text and buttons are in the front all the time, only the background should fadeIn/fadeOut. My english is not perfect, I hope you understand my problem.
Can somebody help me please?
nina_berlini
I have uses 2 elements as background to achieve the effect. Also check demo on https://jsfiddle.net/n380u3cy/1/
HTML:
<div class="container">
<div class="background"></div>
<div class="background"></div>
<button>
Test button
</button>
</div>
CSS:
.container { position: relative; line-height: 100px; }
.container > .background,
.container > .background { position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-size: contain; z-index: 0; }
.container > *:not(.background) { position: relative; z-index: 1; }
Javascript:
var bg=[
'images/best.jpg',
'images/61182.jpg',
'images/bg.jpg'
];
var Transition = 1000;
$('.background').css('background-image','url('+bg[bg.length - 1]+')');
window.setInterval(
function() {
img=bg.shift();
bg.push(img);
var $Backgrounds = $('.background');
$Backgrounds.eq(1).hide(0).css({
'background-image': 'url('+img+')'
}).fadeIn(Transition * .9);
$Backgrounds.eq(0).show(0).fadeOut(Transition, function(){
$(this).show(0).css({
'background-image': 'url('+img+')'
});
$Backgrounds.eq(1).hide(0);
});
}, 2000
);
Make a wrapper and include both the background div and button div inside it with position absolute and the following CSS styles. This way you can control and animate the background separately from the buttons.
var bg = [
'https://placehold.it/1001x201',
'https://placehold.it/1002x202',
'https://placehold.it/1003x203'
];
$('._container-1').css('background-image', 'url(' + bg[2] + ')');
window.setInterval(
function() {
img = bg.shift();
bg.push(img);
document.getElementsByClassName('_container-1')[0].style.backgroundImage = 'url(' + img + ')';
},
10000
);
window.setInterval(
function() {
img = bg.shift();
bg.push(img);
$('._container-1').fadeOut(600, function() {
$('._container-1').css('background-image', 'url(' + img + ')');
$('._container-1').fadeIn(600);
});
},
17000
);
.wrapper {
position: relative;
width: 100%;
height: 200px;
}
._container-1 {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-size: cover;
background-position: top center;
}
.buttons {
position: absolute;
width: 100%;
text-align: center;
bottom: 0;
left: 0;
}
button {
background: red;
padding: 5px 10px;
border: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="_container-1"></div>
<div class="buttons">
<button type="button">
Button 1
</button>
<button type="button">
Button 2
</button>
</div>
</div>
thank you for your great solution. I am not well familiar with jQuery and have a question about your code:
$Backgrounds.eq(1).hide(0).css({
'background-image': 'url('+img+')'
}).fadeIn(Transition * .9);
means it that the second "background-div" first hides, then get a new background-image and after that it ist fadeIn? And means hide(0) that it immediately hides?
nina_berlini
I am trying to create a list of friends and to do this I will need to create a div for each one. The code I tried hasn't worked.
Relevant JavaScript (Now at bottom of page):
document.getElementById("name").innerHTML = user;
document.getElementById("profilePic").src = "users/" + user + "/profilePic.jpg";
var friends = ["Test"];
var friendArea = document.getElementById("friendsDiv");
for (i=0; i < friends.length; i++) {
var friendDiv = document.createElement("div");
friendDiv.setAttribute("class", "friend");
var friendImage = document.createElement("img");
friendImage.setAttribute("class", "friendImage");
friendImage.setAttribute("src", "users/" + friends[i] + "/profilePic.jpg");
friendDiv.appendChild(friendImage);
friendArea.appendChild(friendDiv);
}
Relevant CSS:
.friends {
width: 100%;
height: 90%;
overflow-x: hidden;
overflow-y: auto;
}
.tools {
width: 100%;
height: 10%;
box-shadow: 0px 0px 3px 1px #898989;
}
.friend {
width: 100%;
height: 20%;
padding: 1%;
}
.friendImage {
height: 80%;
width: auto;
border: medium #CCCCCC solid;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
}
The HTML isn't really important but I'll include it anyway.
<div class="window">
<div class="rightCorner">
<img src="images/pPicTemp.png" id="profilePic">
</div>
<div class="holder" id="profileData">
<span id="name"></span>
</div>
<div class="sideBar">
<div class="friends" id="friendsDiv">
</div>
<div class="tools">
</div>
</div>
Is your script in a tag? Also is the document loaded when you attempt this? What does the console says? Is it working with no css? Also if photo path doesnt work there is no other content in the div did you try outputting something else?
You're not appending the friendImage to the friendDiv.
It should look like this:
var friends = ["Test"];
var friendArea = document.getElementById("friends");
for (i=0; i < friends.length; i++) {
var friendDiv = document.createElement("div");
friendDiv.setAttribute("class", "friend");
var friendImage = document.createElement("img");
friendImage.setAttribute("class", "friendImage");
friendImage.setAttribute("src", "users/" + friends[i] + "/profilePic.jpg");
friendDiv.appendChild(friendImage);
friendArea.appendChild(friendDiv);
}
Also, be sure to put this script at the bottom of your HTML <body></body> tag so that the HTML has loaded the entire document before the JavaScript attempts to get elements from the page.
I have a slideshow that pulls its first image from a div, then pulls the rest of the images from an array of list items. I am following a tutorial exactly from The JavaScript Pocket Guide by Burdette (2010 printing), and while everything else works I cannot get any of the pictures after the first to center or align differently. They float left and to the top of the div.
HMTL:
<!DOCTYPE html>
<hmtl class="no-js">
<head>
<title>Slideshow</title>
<link rel="stylesheet" href="slideshow.css" type="text/css" />
<script type="text/javascript">
(function(d, c) { d[c] = d[c].replace(/\bno-js\b/,"js";})(document.documentElement, "className");
</script>
</head>
<body>
<div id="slideshow">
<div class="slides">
<img src="picture01.jpg" width="450" height="336" alt="stuff" />
</div>
<ul>
<li><a href="picture02.jpg" data-size="350x263"</li>
<li><a href="picture03.jpg" data-size="350x263"</li>
<li><a href="picture04.jpg" data-size="350x263"</li>
</ul>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript">
</script>
<script src="slideshow.js" type="text/javascript">
</script>
</body>
</hmtl>
CSS:
#slideshow {
background-color: #103f1c;
width:500px;
height:450px;
margin-left: auto;
margin-right: auto;
top:0px;
position: relative;
}
#slideshow .slides {
position: relative;
margin-left: auto;
margin-right: auto;
width: 450px;
}
#html.js #slideshow .slides img{
position: absolute;
margin-left: auto;
margin-right: auto;
}
#slideshow .next,
#slideshow .prev {
position: absolute;
top: 50%;
margin-top: -0.5em;
width: 40px;
font-size: 32px;
text-decoration: none;
}
#slideshow .next{
right: -50px;
padding-left:10px;
}
#slideshow .prev {
left:-50px;
padding-right: 10px;
text-align: right;
}
JS:
(function($) {
// Include utility jQuery plug-ins
$.fn.tallest = function(outer, margins) {
var fn = outer ? "height" : "outerHeight";
return Math.max.apply(Math, $.map(this, function(el) {
return $(el)[fn](margins);
}));
};
$.fn.widest = function(outer, margins) {
var fn = outer ? "width" : "outerWidth";
return Math.max.apply(Math, $.map(this, function(el) {
return $(el)[fn](margins);
}));
};
// Declare initial variables
var slideshow = $("#slideshow");
var slides = slideshow.find(".slides");
var currentImageIndex = 0;
// Create images from the link list
slideshow.find("ul a").each(function() {
var link = $(this);
var size = link.attr("data-size").split("x");
$("<img />").attr({
src : link.attr("href"),
width : size[0],
height : size[1],
alt : link.text()
}).hide().appendTo(slides);
});
// Collect all images in one node set and hide the list
var images = slides.find("img");
slideshow.find("ul").hide();
// Resize slides <div> to hold the largest images
var slidesWidth = images.widest();
var slidesHeight = images.tallest();
slides.css({
width : slidesWidth,
height : slidesHeight
});
// Center each image
images.each(function() {
var image = $(this);
image.css({
left: slidesHeight / 2 - image.width() / 2,
top: slidesHeight / 2 - image.height() / 2,
});
});
// Save a reference to the first image
var activeImage = images.eq(currentImageIndex);
// The function to show the next or previous image
function showImage(newIndex) {
currentImageIndex = newIndex >= images.length ? 0 : newIndex;
currentImageIndex = currentImageIndex < 0 ? images.length - 1 : currentImageIndex;
activeImage.fadeOut(0);
activeImage = images.eq(currentImageIndex).fadeIn(150);
}
// Start timer to cycle through images
var interval = setInterval(function() {
showImage(currentImageIndex + 1);
}, 5000);
// Create next and previous controls
$('\u232A').appendTo(slides).bind("click", +1, onClick);
$('\u2329').appendTo(slides).bind("click", -1, onClick);
// The event handler for the controls
function onClick(event) {
event.preventDefault();
clearInterval(interval);
showImage(currentImageIndex + event.data);
}
})(jQuery); // Self-invoking function executes automatically
The main problem here is in your CSS:
#html.js #slideshow .slides img{
position: absolute;
margin-left: auto;
margin-right: auto;
}
Margin: auto; will only work on objects that have a defined width. Since an image is a replaced inline-block, no real width exists. This is made worse by the fact that you've positioned it absolutely, which changes the way margins will work - the item will always pick up its position relative to the determined parent, and apply margins after that outside of the flow, so auto will not be relevant.
first step is to remove the absolute positioning on the image, it's not useful here.
By default, images are a type of inline-block, so simply adding "text-align:center;" to the "#slideshow .slides" selector will center the images.
Alternately, if we just want to edit the images and force them to center themselves, change the above block to:
#html.js #slideshow .slides img{
display:block;
margin-left: auto;
margin-right: auto;
}
and everything should line up like you wanted.
I'm trying to write a facebook like chatbox, but i've encountered a small problem.
I'm using the following code (it's only test code, so it's not really clean):
css code:
#messenger {
position: fixed;
bottom: 0px;
right: 10px;
width: 200px;
height: 300px;
z-index: 4;
background-color: #ECECEC;
border: 1px solid #000;
}
#messenger.p {
text-align: right;
}
#contacts {
margin: 5px 5px 5px 5px;
}
#chatspace {
position: fixed;
bottom: 0px;
right: 240px;
height: 20px;
left: 20px;
background-color: #ECECEC;
border: 1px solid #000;
z-index: 4;
}
.chatbox {
position: absolute;
bottom: 0px;
width: 200px;
height: 200px;
z-index: 4;
background-color: #ECECEC;
border: 1px solid #000;
}
html/javascript code:
<script type="text/javascript">
var i = 0;
function oc_chatbox() {
if (i == 0) {
document.getElementById('contacts').style.visibility = 'hidden';
document.getElementById('messenger').style.height = '20px';
i = 1;
}
else {
document.getElementById('contacts').style.visibility = 'visible';
document.getElementById('messenger').style.height = '300px';
i = 0;
}
}
function new_chat(userid) {
var new_right;
new_right = document.getElementById('messenger').style.right;
//alert('old value: '+ new_right);
new_right += 20;
//alert('New value of right: '+ new_right);
document.getElementById('chatspace').innerHTML = '<div id="'+userid+'" class="chatbox" style="right: '+new_right+'px;"></div>';
//document.write('<div id="'+userid+'" class="chatbox" style="right: '+new_right+'px;"></div>');
}
</script>
<div id="chatspace"></div>
<div id="messenger">
<p>Collapse</p>
<div id="contacts">
<ul>
<li>contact A</li>
</ul>
</div>
</div>
the problem is, that when I try to add new chats to the chatbar, i can't seem the place them next to each other.
anyone who can help ?
EDIT:
so i changed to javascript code to:
var last = null;
function new_chat(userid) {
if(userid==null)
userid = "user666";
var new_right;
var margin = 10;
var messenger = window.last==null?document.getElementById('messenger'):window.last; //Take the messenger or the last added chat
new_right = document.body.clientWidth-messenger.offsetLeft; //Compute the window size
console.log(new_right); //Log the number
new_right += margin; //keep spaces between divs
var newChat = document.createElement("div"); //DOM create DIV
newChat.id = userid;
newChat.className = "chatbox shadow";
newChat.style.right = new_right+"px";
newChat.innerHTML = '<p>'+userid+'</p><p><textarea></textarea></p>';
window.last = newChat; //Remember whichever is last
document.body.appendChild(newChat);
}
and now it works, thanks !
You cannot get an element right offset using its style, unlest the style is set and valid. Instead you must get element.offsetLeft and size of window area and do this:
new_right = windowSize()[0]-messenger.offsetLeft;
Where window size is this function.
Here is my, working, version of your function:
var last = null;
function new_chat(userid) {
if(userid==null)
userid = "user666";
var new_right;
var margin = 20;
var messenger = window.last==null?document.getElementById('messenger'):window.last; //Take the messenger or the last added chat
new_right = windowSize()[0]-messenger.offsetLeft; //Compute the window size
console.log(new_right); //Log the number
new_right += margin; //keep spaces between divs
var newChat = document.createElement("div"); //DOM create DIV
newChat.id = userid;
newChat.className = "chatbox";
newChat.style.right = new_right+"px";
window.last = newChat; //Remember whichever is last
document.body.appendChild(newChat);
}
You may get errors if console is not defined in your brouwser. But in such case you should take a better browser. Normally, the if(console!=null) is put in code.
And here is the link.
You should try adding a float style.
.chatbox {
float: right;
}
Add that to your chatbox styles. You may need to mess around a bit to make sure the float doesn't mess with your other elements. You may need a better container for them.
If you want to get really fun, you can add .draggable() from jQuery, and you can have them snap to your chat bar. You can then change the order of your chats.