how do I cycle through background images by clicking a button? - javascript

I want to preview some backgrounds by using a button to cycle through them, just not very good at the js. I have them named "1"-"13". I wanted to step through them. When I get to "13" I want it to set it back to "1" when "next" is clicked and when "prev" is clicked when it gets to "1" to set it to "13". This is what I've tried but I know my syntax is wrong for the js.
HTML
<button id="n" class="b">NEXT</button>
<button id="p" class="b">PREV</button>
CSS
body {
background:black;
}
.b {
background:black;
color:white;
}
JS
$(document).ready(function(){
var i = 1;
$("#n").click(function() {
alert(i);
i++;
$('body').css("background-image", "url(../images/bg/ " + i + " .png)");
if (i===14){i=1;};
});
$("#p").click(function() {
alert(i);
i--;
$('body').css("background-image", "url(../images/bg/ " + i + " .png)");
if (i===0){i=13;};
});
});
Still working on it but some help would be nice getting it done faster.
http://jsfiddle.net/80nz56wy/ I guess a jsfiddle won't help much if I'm using local content.

You should also try this. Here conditions are written before setting CSS, which will check first and then assign the image path.
$(document).ready(function() {
var i = 0;
$("#n").click(function() {
i++;
if (i > 13){ i = 1; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
//if (i === 13){ i = 1; };
});
$("#p").click(function() {
i--;
if (i <= 0) { i = 13; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
//if (i === 1) { i = 13; };
});
});
Other wise you may get wrong image paths, something like:
images/bg/0.png
or
images/bg/-1.png

Change Your javascript coding as below..
var i = 1;
$("#n").click(function() {
$('body').css("background-image", "bg" + i +".png");
i=i+1;
if (i==13){i=1};
});
$("#p").click(function() {
$('body').css("background-image", "bg" + i +".png");
i=i-1;
if (i==1){i=13};
});

Here it is, not sure what I changed the 20 times I edited the same line over and over but I must have gone full retard earlier.
$(document).ready(function(){
var i = 0;
$("#n").click(function() {
i++;
if ( i > 13 ){ i = 1; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
});
$("#p").click(function() {
i--;
if ( i <= 0 ){ i = 13; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
});
});

Related

jQuery Animated Text Colors

I'm trying to get each letter color to swap from red to green and back to red.
What I have now works, but I don't like the fading, is there a better way to do this?
const ltr = $('h1').text().split('');
function colorChange() {
$( 'h1' ).fadeOut(500, function() {
redGreen();
}).fadeIn(500).fadeOut(500, function() {
greenRed();
}).fadeIn(500);
}
setInterval( function() {
colorChange();
}, 1);
function redGreen() {
$('h1').text('');
for(var i = 0; i < ltr.length; i++) {
if(i % 2 == 0) {
$('h1').append('<span class="red">' + ltr[i] + '</span>');
} else {
$('h1').append('<span class="green">' + ltr[i] + '</span>');
}
}
}
function greenRed() {
$('h1').text('');
for(var i = 0; i < ltr.length; i++) {
if(i % 2 == 0) {
$('h1').append('<span class="green">' + ltr[i] + '</span>');
} else {
$('h1').append('<span class="red">' + ltr[i] + '</span>');
}
}
}
Referred to the solution for toggling class animation here : ToggleClass animate jQuery?. You should change your colorChange function to something like this :
function colorChange() {
$( 'h1 > span' ).toggleClass( "red green", 1000, "easeInOutQuad" );
}
And make sure you build the spans at the beginning with alternative classes to each item (use one of your redGreen() or greenRed() function for the first time only).
Check this Fiddle
You need to include jQuery UI to have the effect.
I managed to remove the fade effect by using setTimeout.
See the plunker here

jQuery bug when using bounce effect

I have problem with jQuery bounce effect. Every thing works good when there is no bounce - with bounce, when You move very fast many times on button - in sometime, box just doesn't hide. What is wrong in this jsfiddle?
My jsfiddle:
http://jsfiddle.net/d6mSA/170/
My JS:
$('.flex_section').delegate('a','mouseenter mouseleave',function(e){
var a = $(this).attr('id');
if (e.type == 'mouseenter'){
clearTimeout(t_on)
if (a == 'abc'){
clearTimeout(t_off)
t_on = setTimeout(function() { popup_show(a,t_on); }, 10);
}
} else {
t_off = setTimeout(function() { popup_remove(a,t_off); }, 1000);
}
)}
function popup_show(type,string){
if (type == 'abc'){
$('#pc_' + type).css('display','block');
$('#pc_' + type).effect( "bounce",{times:3,distance:20},1000);
}
clearTimeout(string);
}
function popup_remove(type,string){
$('#pc_' + type).css('display','none');
clearTimeout(string)
}
Keep it simple:
function popup(){
$('.flex_top a').hover(function(){
var type = $(this).attr('id');
var offset = $('#' + type).offset();
$('#id_' + type).css('display','block')
.offset({left:offset.left + 100, top:offset.top + 380})
.effect( "bounce",{times:3,distance:20},1000);
},function(){
var type = $(this).attr('id');
$('#id_' + type).fadeOut();
}
);
}
And dont call many times the same object search $('#id_' + type)
Try using stop
$('#pc_' + type).stop().effect( "bounce",{times:3,distance:20},1000);

Unable to get proper element count on drop

I have noticed at several attempts to get a count of dropped elements it always returns one less than the number found, but if I try the same command via Chromes console I get the propper response.
I assume the DOM is not updated when this script runs so I threw a timeout/try again mechanism but still with no avail. What am I missing?
Expected Result size = 10
Actual Result size = 9
Code
var asmCount = 0;
function storeValues(values, tryNumber){
var size = values.length,
tryNumber = (!isNaN(tryNumber)) ? tryNumber : 1
;
console.log('full boat:' + size + ', try #'+ tryNumber + ' ' + typeof(tryNumber));
if(tryNumber > 60){
console.log('too many tries');
return;
}
if(size < 10){
console.log('missing entries');
tryNumber = tryNumber + 1;
setTimeout(storeValues($('.asm-ranking .receiver .asm-value'), tryNumber) , 500);
} else if(size > 10){
console.log('too many entries, something broke');
} else {
console.log('just right, lets do this shit.');
//$.each(values, function(k,v){ console.log($(v).data('id'));});
}
}
$('.asm-ranking .receiver').droppable({
drop: function(event,ui){
var _self = this,
receiverCount = $('.asm-ranking .receiver li').length
;
//console.log('event',event);
//console.log('ui', ui);
asmCount++;
console.log(asmCount + ' / ' + receiverCount);
if(receiverCount == asmCount){
storeValues($('.asm-ranking .receiver .asm-value'), 1); // give DOM time to catch up, then store
}
}
});
for some reason when I wrapped my jQuery notation in with document ready
$(document).ready(function{ ... })
it works as expected.

jquery prototype for a commonly used function

I'm not too experienced in JQuery beyond standard api functionality, but I have a number of scrollers on my page which all use the same code, only they each have a few of their own settings (for example, separate heights and scroll limits, and current number of times they have been scrolled). I want to be able to use the code over and over again, but with each reference receiving its own set of variables. I think that prototypes are what I'm after, but I can't quite wrap my head around the examples I've seen of this. This is my scroller code:
$(document).ready(function() {
var scrollAmt = 50; //distance in pixels;
var scrollableAmt = $('#weblinks .container').outerHeight();
var viewAmt = $('#weblinks').outerHeight();
var maxScroll = Math.ceil((scrollableAmt-viewAmt) / scrollAmt);
var currentItem = 0;
function setScrollButtons(scrollRef,scrollAmount){
}
$("#weblinks .scrollDownBtn").click(function(){
if (currentItem <= maxScroll){
$('#weblinks .container:not(:animated)').animate({'top' : '-='+ scrollAmt + ''},500,function(){
currentItem++
});
} else {
currentItem = 0;
$('#weblinks .container:not(:animated)').animate({'top' : currentItem},500);
}
});
$("#weblinks .scrollUpBtn").click(function(){
if (currentItem > 0){
$('#weblinks .container:not(:animated)').animate({'top' : '+='+ scrollAmt + ''},500,function(){
currentItem--;
});
} else {
$('#weblinks .container:not(:animated)').animate({'top' : currentItem},500);
}
});
});
So essentially what I'd want to do is create a function or class, I guess, which accomplishes all of the above code, but be able to pass it a div reference to take the place of #weblinks, and maybe pass it a scroll amount, and multiple instances of this functionality be able to exist on the same page together. Anybody have any advice about the best way to go about this?
EDIT: I've added the HTML that will always exist for each scroller.
<div id="weblinks" class="scrollbar_container">
<div class="customScrollBox">
<div class="container">
<div class="content">
</div>
</div>
<a class="scrollUpBtn" href="javascript:void(0);"></a> <a class="scrollDownBtn" href="javascript:void(0);"></a>
</div>
</div>
My Bid:
(function($){
$.fn.extend({
customScroller: function(options){
return this.each(function(i,e){
var container = $(e).find('.container'),
content = $(e).find('.content'),
scrollUpBtn = $(e).find('.scrollUpBtn'),
scrollDownBtn = $(e).find('.scrollDownBtn');
var self = $(e);
var o = $.extend({}, $.fn.customScroller.defaults, options);
o.scrollableAmt = container.outerHeight();
o.viewAmt = self.outerHeight();
o.maxScroll = Math.ceil((o.scrollableAmt - o.viewAmt) / o.scrollAmt);
scrollDownBtn.click(function(){
console.log('DOWN -- current: '+o.currentItem);
if (o.currentItem <= o.maxScroll){
container.filter(':not(:animated)').animate({
top: '-='+o.scrollAmt
},500,function(){
o.currentItem++;
});
}else{
o.currentItem = 0;
container.filter(':not(:animated)').animate({
top: o.currentItem
},500);
}
});
scrollUpBtn.click(function(){
console.log('UP -- current: '+o.currentItem);
if (o.currentItem > 0){
container.filter(':not(:animated)').animate({
top: '+='+o.scrollAmt
},500,function(){
o.currentItem--;
});
}else{
container.filter(':not(:animated)').animate({
top: o.currentItem
},500);
}
});
});
}
});
$.fn.customScroller.defaults = {
scrollAmt: 50,
scrollableAmt: 0,
viewAmt: 0,
maxScroll: 0,
currentItem: 0
};
})(jQuery);
$('#weblinks').customScroller();
To answer your question, I use extend in a couple of places: one for the options, and the other for jQuery addon ability.
$.fn.extend tells jQuery this is extending its functionality.
$.extend({},$.fn.customScroller.defaults, option); allows you to call .customScroller({ scrollAmount: 10 }) and change the behavior of the scroll.
any other questions, please just ask.
This is a good candidate for jQuery plugin you can create for yourself. Of course if you want to spend some time and learn this principle :)
How to develop a jQuery plugin for some details of what and how jQuery plugins do
You could pretty simply refactor it in the case that all div's will have a sub container class. Something like:
function scrollExample(divId) {
var scrollAmt = 50; //distance in pixels;
var scrollableAmt = $(divId + ' .container').outerHeight();
var viewAmt = $(divId).outerHeight();
var maxScroll = Math.ceil((scrollableAmt-viewAmt) / scrollAmt);
var currentItem = 0;
function setScrollButtons(scrollRef,scrollAmount){
}
$(divId + " .scrollDownBtn").click(function(){
if (currentItem <= maxScroll){
$(divId + ' .container:not(:animated)').animate({'top' : '-='+ scrollAmt + ''},500,function(){
currentItem++
});
} else {
currentItem = 0;
$(divId + ' .container:not(:animated)').animate({'top' : currentItem},500);
}
});
$(divId + " .scrollUpBtn").click(function(){
if (currentItem > 0){
$(divId + ' .container:not(:animated)').animate({'top' : '+='+ scrollAmt + ''},500,function(){
currentItem--;
});
} else {
$(divId + ' .container:not(:animated)').animate({'top' : currentItem},500);
}
});
});
Then call it with something like:
$(document).ready(function() {
scrollExample('#webLinks');
}
If you had the actual reference to the object it would be slightly different, but still follow a similar principle.

Javascript Focus() function not working

I have a textbox which I want to set the focus on, but it doesn't work.
document.getElementById("txtCity").focus();
Any idea?
Maybe you are calling the JavaScript before the input element is rendered? Position the input element before the JavaScript or wait until the page is loaded before you trigger your JavaScript.
In that order, it works just fine:
<input type="text" id="test" />
<script type="text/javascript">
document.getElementById("test").focus();
</script>
In jQuery you could place your code within the .ready() method to execute your code first when the DOM is fully loaded:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#test").focus();
// document.getElementById("test").focus();
});
</script>
In case someone searching has a similar situation to mine ... I had to set a tabindex attribute before my div could receive focus():
featured.setAttribute('tabindex', '0');
featured.focus();
console.log(document.activeElement===featured); // true
(I found my answer here: Make div element receive focus )
And of course, make sure the body element is ready before setting focus to a child element.
I have also faced same problem.To resolve this problem, put your code in setTimeout function.
function showMeOnClick() {
// Set text filed focus after some delay
setTimeout(function() { jQuery('#searchTF').focus() }, 20);
// Do your work.....
}
Try to wrap it into document ready function and be sure, that you have jquery included.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#test").focus();
});
</script>
<div id="txtROSComments" contenteditable="true" onkeyup="SentenceCase(this, event)"style="border: 1px solid black; height: 200px; width: 200px;">
</div>
<script type="text/javascript">
function SentenceCase(inField, e) {
debugger;
var charCode;
if (e && e.which) {
charCode = e.which;
} else if (window.event) {
e = window.event;
charCode = e.keyCode;
}
if (charCode == 190) {
format();
}
}
function format() {
debugger; ;
var result = document.getElementById('txtROSComments').innerHTML.split(".");
var finaltxt = "";
var toformat = result[result.length - 2];
result[0] = result[0].substring(0, 1).toUpperCase() + result[0].slice(1);
if (toformat[0] != " ") {
for (var i = 0; i < result.length - 1; i++) {
finaltxt += result[i] + ".";
}
document.getElementById('txtROSComments').innerHTML = finaltxt;
alert(finaltxt);
abc();
return finaltxt;
}
if (toformat[0].toString() == " ") {
debugger;
var upped = toformat.substring(1, 2).toUpperCase();
var formatted = " " + upped + toformat.slice(2);
for (var i = 0; i < result.length - 1; i++) {
if (i == (result.length - 2)) {
finaltxt += formatted + ".";
}
else {
finaltxt += result[i] + ".";
}
}
}
else {
debugger;
var upped = toformat.substring(0, 1).toUpperCase();
var formatted = " " + upped + toformat.slice(1);
for (var i = 0; i < result.length - 1; i++) {
if (i == (result.length - 2)) {
finaltxt += formatted + ".";
}
else {
//if(i
finaltxt += result[i] + ".";
}
}
}
debugger;
document.getElementById('txtROSComments').value = finaltxt;
return finaltxt;
}
</script>
<script type="text/javascript">
function abc() {
document.getElementById("#txtROSComments").focus();
}
It works fine in this example
http://jsfiddle.net/lmcculley/rYfvQ/

Categories