Im trying to make a "spinner" much like on csgoempire.com, but I'm having some issues (I'm almost totally new to JS and I'm not good at HTML). I have tried a bunch of stuff like making one div for each picture, and having a separate JS function for each, but after some thinking I realised that it wouldn't be efficient at all and it would make it hard to change stuff later. I then decided to make separate divs for each photo, but placing them all in another div which would be moved by the JS function. This would make it a lot more efficient than before, but I can't seem to get it to work, and there are (hopefully) better ways of doing it. Id really appreciate some tips on how I can make it more efficient, and a fix for my current problem :)
Here is the code in all its glory:
console.log("Connected to server.")
function spin() {
console.log("Starting Spin.");
var boxElement = document.getElementById('allBoxes');
var pos = 900;
var id = id;
setInterval(frame, 1);
function frame() {
if (pos == 100) {
clearInterval(id)
} else {
pos--;
boxElement.style.left = pos + 'px';
}
}
}
<div id="allBoxes">
<div id="box2" style="position:absolute; left:712pt; top:150pt; width:50px; height:50px;"><img src="http://www.theaa.ie/winterhub/wp-content/uploads/2015/12/AA-logo-50x50.png" /></div>
<div id="box1" style="position:absolute; left:675pt; top:150pt; width:50px; height:50px;"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAMAAAAp4XiDAAAALVBMVEXGAA4fHx////98fHz8/Pzy8vItLS1xcXFnZ2eIiIhdXV2PCxQtHR64Aw9XFRmYSViLAAAAnklEQVRIie2UyQ6DMAxEyZAd2v//3JolAuWQdKyqAok5WDn4ZRQvGYZHj0SmqTsivs71PSS7KBEwJUaX24h3sOGMBAvn2y7RAuOBjICNvbcEAKkgckDoV0wuRkGwWH5R5HRGUr/I2FWff4toun9V5G8VY1upGRh+LPnh16wYv8ia70LR/SsilaaZSN71etNIMaKQzYhDViMWESMauZE+q+cGCDwyhBUAAAAASUVORK5CYII="
/></div>
</div>
<button onclick="spin()"> Click Me! </button>
This was made by just googling around, and testing stuff, so I'm sure its insanely bad and inefficient :P (I dont even know if its possible to do what I want to do this way.. )
The issue is that the spinner won't spin anymore.. It does when I move them separately, but not when they are both inside a div, and I move said div. Is there a way to move multiple divs by only moving one of them? Can you recommend another way of doing this if you know a better way that is more.. dynamic?
The end goal is to fetch each user's image from steam and use those images in the "spinner", make an arrow that points to the middle that will output the username of the person it lands on and have the "spinner" start once a timer reaches 0, but for now I'm just trying to learn, and I figured that the best way to learn is to have a project to work on.. (may have picked a bit of a difficult project though..)
You didn't save the interval so you can stop it:
...
var pos = 900;
var id = setInterval(frame, 1);
function frame() {
...
Made a jsFiddle with the solution: https://jsfiddle.net/bfrhw7rf/1/
Consider using css to create the spinner, like here: https://projects.lukehaas.me/css-loaders/
Since you are using a very short interval you are using up the single thread that runs your javascript, with css you are not blocking the rest of your code.
Related
I dont have much experience in javascript but trying to achieve a slideshow like in https://district2.studio/ where the text and image changes as you scroll. In the example no matter the amount you scroll at a time or inbetween the image changing animation, the image will change only once at a time. I'm trying to achieve this using javascript only and no additional plugin or libraries. Hope someone can help me.
You have some errors.
First of all, you have to wait the DOM is ready. You could movet he entire before de body tag closes to ensure that or use window.onload
class prop elements it's an array.
window.onload = function() {
document.getElementById("image1").onscroll = function() {
if(document.getElementById("image2").classList.contains("scroll")){
document.getElementById("image2").classList.remove("scroll");
} else {
document.getElementById("image2").classList.add("scroll");
}
};
}
Something like this should work
I'm building my new webcomics home on my website and have ran smack into a wall.
Here's what I want and what I've tried.
I'm trying to have something where using JavaScript I can make only the image of the comic change so that I do not have to make a new page for every single image. I don't mind having to do extra coding work as long as I don't have hundreds of pages in my directory.
I was going to have a /First Next Prev Last/ kind of navigation but I've been so frustrated with it that I kind of scrapped that idea for now and instead am thinking of having a list of the names + link of each comic below the image and just put that into a scroll box. Kinda like how Perry Bible Fellowship works.
I've been trying to figure out if maybe an array is the way to go as I have around 30 images so far and I will be updating daily. Honestly I don't even know if Javascript is the way to go either.
I've also tried to implement [this code](http://interestingwebs.blogspot.com/2012/09/change-image-onclick-with-javascript.html
) to see if it would work and it just seems to break as soon as I try to plug in my own stuff into it. Here's an example of my javascript butcher job:
<script language="javascript">
function Drpepper()
{
document.getElementById("image").src = "/comics/1DrPepper.jpg";
}
function Applestore()
{
document.getElementById("image").src = "/comics/2Applestore.jpg";
}
</script>
<p>
<img alt="Dr Pepper" src="1DrPepper.jpg"
style="height: 85px; width: 198px" id="image" /></p>
<p>
<input id="Button1" type="button" value="Dr Pepper" onclick="DrPepper()"/>
<input id="Button2" type="button" value="Apple Store" onclick="Applestore()" /></p>
Is there anyway to expand this for my purposes? What I would like is to not have buttons and just use links but I can't seem to get beyond this part here where the image doesn't even load and the buttons do nothing.
Also if there is some better way of doing this using any other method other than JavaScript, I'm more than open to it, except the aforementioned making hundreds of pages.
First off, consider using jQuery if you're going to go the Javascript route. Here's an example I mocked up for you:
// set up an array of comic images
var imgs = [
'http://dustinland.com/dlands/dland.sxsw.jpg',
'http://dustinland.com/dlands/dland.hipster.jpg',
'http://dustinland.com/dlands/dland.legalize.marijuana.jpg',
'http://dustinland.com/dlands/dland.TLDR.jpg'
],
// initialize current to 0
current = 0;
// define a function that returns the next item in the imgs array,
// or the first if we're already at the last one
function next() {
current++;
if (current >= imgs.length) current = 0;
return imgs[current];
}
// define a function to do the opposite of next()
function prev() {
current--;
if (current < 0) current = imgs.length - 1;
return imgs[current];
}
// define the first image in terms of a jquery object
var comic = $('<img/>').attr('src', imgs[0]);
// append to DOM
$('#comics').append(comic);
// click the prev button, get the previous image
$('#prev').on('click', function(){
comic.attr('src', prev());
});
// click the next button, get the next image
$('#next').on('click', function(){
comic.attr('src', next());
});
See this in action here: http://jsfiddle.net/QzWV5/
This may work fine for your application, but maybe you should consider the advice of #icktoofay; using Javascript will mean, at the very least, that Google won't automatically crawl all your images. This also presents a usability problem: do you want to force your users to click through every comic in order to reach the first? It's probably best if every image were reachable via its own URL, that way, anyone who came across your comic on the web could easily link to an individual comic.
Have you considered using Tumblr, Blogger, or Wordpress?
I'm trying to build an auto playing slideshow from scratch, both for a site I'm working on and as a learning exercise. As such I want to learn how to do it myself and not resort to using a plugin or one of the many excellent freely available slideshows. Here's what I've got so far:
http://jsfiddle.net/mandrill/zTdxs/15/
Heres the JS:
$("#s1").css("display", "block"); // displays slide one as default on page load
$("#slideshow").click(function () {
$(".slide").each(function (index) {
var n = index + 1;
$("#s" + n).toggle("fade");
return index;
});
});
It's currently just switching between slide one and all the other slides. How do I get it to cycle through the slides in order in a continuous loop?
As with any piece of code, if you're not sure how to do it (but are looking for a learning experience) then there's no better way of learning that looking at real live code already written. Get the (un-minified) versions of a few slideshows that you find and read the code.
My favourite slideshow plugin is the cycle one - there's a light version with fairly readable code: http://malsup.github.com/jquery.cycle.lite.js
To give you a more specific answer to your particular question, you can reset the index back to the start.
I figured out how to do it. My lack of understanding of loops was my downfall. The .each() function is not required. Here's the working JS:
$("#s1").css("display","block").addClass("active");
$("#slideshow").click(function(){
var currentSlide = $(".active").attr("id");
if ($("#slideshow .slide:last").hasClass("active")) {
$(".active").toggle("fade").removeClass("active");
$("#slideshow .slide:first").toggle("fade").addClass("active");
} else {
$(".active").toggle("fade").removeClass("active");
$("#"+currentSlide).next(".slide").toggle("fade").addClass("active");
}
});
It can be seen in action here: http://jsfiddle.net/mandrill/wLTns/6/
Thanks to all for their input :) Next step: making it autoplay and adding a timer...
Currently, homepage text is only displayed via a click function which initiates a slide out.
What I would like to do, is to change this so that it doesn't require a click to display. I'm wanting the text to display (fade in) after about 3 seconds of the page loading.
This is what I have at present:-
$('.introbox span').replaceWith(function(){
return '\
<div class="slideOutTip '+$(this).attr('class')+'" style="'+$(this).attr('style')+'">\
\
<div class="tipVisible">\
<div class="tipIcon"><div class="plusIcon"></div></div>\
<span class="tipTitle">'+$(this).attr('title')+'</span>\
</div>\
\
<div class="slideOutContent">\
<p>'+$(this).html()+'</p>\
</div>\
</div>';
});
It is when the 'plusIcon' is clicked, that the text slides out and is visible.
The listen out for the click function is...
$('.tipVisible').bind('click',function(){
var tip = $(this).parent();
So I'm presuming this is where I need to convert the necessary to use autoload with perhaps a setDelay and FadeIn although I'm not 100%.
Please could someone advise how this can be altered to not use a click but auto display after delay? Thanks in advance.
Attempted to add code in jsfiddle if it is easier to see what I'm trying to do - thanks.
Pretty simple: make a function with what you do at .tipVisible.click and then set a window.setTimeout(yourFunction, 3000);
#Comment: Your JS is already pretty complex, I probably would reorganize and recode everything so I can just give you a hint how it could be implemented (didn't work right away when I added it in your fiddle, but I'm a bit too lazy to find the problem there).
var animate = function(obj) {
var tip = obj ? $(obj).parent() : $(".tipVisible").parent();
/* If a open/close animation is in progress, exit the function */
if (tip.is(':animated')) return false;
if (tip.find('.slideOutContent').css('display') == 'none') {
tip.trigger('slideOut');
}
else tip.trigger('slideIn');
}
window.setTimeout( animate, 3000);
$('.tipVisible').bind('click', function() {
animate(this);
});
EDIT: Well this is doing something at least, now you have to figure out what needs to be done when and how ;)
PS: You used jQuery but loaded Mootools framework... Mootools doesn't know $(document).ready()
I have a slightly vague question. I have the following in my code: http://jsfiddle.net/PMnmw/2/
In the jsfiddle example, it runs smoothly. The images are swapped quickly and without any hassle. When it is in my codebase though, there is a definite lag.
I'm trying to figure out why that lag is happening. The structure of the jquery is exactly the same as above. I.e. Inside the $(document).ready (...) function, I have a check to see if the user clicked on the img (based on the classname) and then I execute the same code as in the jsfiddle.
I'm at my wits end trying to figure out what to do here... Clearly I'm not doing the swap right, or I'm being very heavy handed in doing it. Prior to this, one of my colleagues was using AJAX to do the swap, but that seems to be even more heavy duty (a full fledged get request to get the other icon...).
I've modified your fiddle: http://jsfiddle.net/PMnmw/12/
Things I've optimized:
Created a variable for both img1 and img2, so that you won't have to navigate the DOM to reference those two images anymore, thusly improving performance.
Applied a click handler to the images themselves, so you don't have to search the children of the wrapper.
The basic idea was to reduce the number of jquery selections as much as possible.
Let me know if this helped speed things up.
$(document).ready(function() {
var img1 = $('#img1');
var img2 = $('#img2');
$(".toggle_img").click(function(e) {
var target = $(e.target);
if(target.is(img1)){
img1.hide();
img2.show();
}
else if (target.is(img2)) {
img2.hide();
img1.show();
}
});
});
Images that are not visible are normally not loaded by the browser before they are made visible. If there seems to be a problem, start by downloading an image optimizer like RIOT or pngCrush to optimize your images.
If it's only two arrows, you should consider joining them into a CSS sprite.
You could try not doing everything with jQuery, but it shouldn't really make that much difference.
Something like this maybe, with the hidden image loaded in JS and some traversing done outside jQuery (but that is probably not the problem, although the code seems overly long for a simple image swap?) :
$(document).ready(function() {
var img=new Image();
img.src='http://i.imgur.com/ZFSRC.png'; //hidden image url
$(".wrapper").click(function(e) {
if(e.target.className=='toggle_img') {
$('.toggle_img').toggle();
if (e.target.parentNode.childNodes[1].style.display=='none') {
console.log("hello");
} else {
console.log("goodbye");
}
}
});
});
FIDDLE