Jquery - add function to jquery - javascript

Hey there i got this fiddle :
http://jsfiddle.net/5H5Xq/42/
containing this jquery:
function anim(selector) {
$(".images img", selector).first().appendTo($('.images', selector)).fadeOut(2000);
$(".images img", selector).first().fadeIn(2000);
}
// Untuk delay gambarnya
var i = 0, max = 3;
myFunction = function(event){
$(".subbox1").each(function() {anim(this)});
i += 1;
if(i >= max) { i = 0; }
}
var interval = setInterval(myFunction, 5000);
$(".slider").hover(function() {
clearInterval(interval);
var img = $('<img>');
img.attr('src', $(this).attr('data-url'));
$('#newImage').html(img);
$('.images').hide();
return false;
i += 1;
$(".subbox1").each(function() {anim(this)});
});
$(".slider").mouseout(
function (){
$('.images').show();
// $('#newImage').hide();
interval = setInterval(myFunction, 5000);
}
);
It just means:
Every 5 seconds => automatic image-change.
When i hover throw a link => image-change + automatic image change disabled.
What i wanted to add to the automatic image-change:
Depending on the current picture, the -item gets a new background-color..is this possible?
greetings

Sure you can. Just change the background-color css attribute of the element depending on your criteria.
if (*your criteria here*) {
element.css("background-color", "#ff0000");
}

Related

Selecting random div for auto fade in and fade out

Currently, this code is auto fade in and fade out div by selecting the div element the way they were arranged (consecutive order). What I want to do now is to make the selector in random, I want to fade in a random div and after fading it out it will pick another random div and infinite loop the process. Since I'm new in jQuery and so confused, I also want to know your opinion on how to put this such process on a If Else statement in the easiest way. Like for example, I will get the value of a number
int num = 1;
If(num == 1){
<!-- Do the process-->
}
Else {
<!-- Do another process by selecting from another set of divs-->
}
Here is the code:
jQuery.fn.nextOrFirst = function (selector) {
var next = this.next(selector);
return (next.length) ? next : this.prevAll(selector).last();
}
$(document).ready(function () {
$('div.mb').fadeOut(500);
var fadeInTime = 1000;
var intervaltime = 3000;
setTimeout(function () {
fadeMe($('div.mb').first());
}, intervaltime);
function fadeMe(div) {
div.fadeIn(fadeInTime, function () {
div.fadeOut(fadeInTime);
setTimeout(function () {
fadeMe(div.nextOrFirst());
}, intervaltime);
});
}
});
Divs:
<div class="boxes">
<div class="mb one">1-------------one</div>
<div class="mb two">2-------------two</div>
<div class="mb three">3-------------three</div>
</div>
Not sure if this is exactly what you want but can be modified:
var mb = $('.mb'),
mbl = mb.length;
mb.hide();
rand();
function rand(){
var r = getRand(0, mbl);
mb.eq(r).fadeIn('slow', function(){
$(this).fadeOut('slow', function(){
setTimeout(rand, 200);
});
});
}
function getRand(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
Try changing the nextOrFirst function to something like:
jQuery.fn.nextOrFirst = function (selector) {
var xCount = selector.size();
return Math.floor(Math.random() * xCount ) + 1;
}
Instead of getting the next of first div, this gets a count of all of the divs,
and pics a random number between 1 and X(the number of divs with your selector)
Try something like this,Hope it helps
var c=$(".boxes div");
setInterval(function(){
$.each(c,function(a,z){
$("div[class='"+(z.className)+"'").fadeIn();
});
var item = c[Math.floor(Math.random()*c.length)];
var u=item.className;
$("."+u).fadeOut();
$("div[class='"+u+"'").fadeOut(1000);
}, 3000);
EDIT:
var c=$(".boxes div");
setInterval(function(){
$.each(c,function(a,z){
$("div[class='"+(z.className)+"'").hide();
});
var item = c[Math.floor(Math.random()*c.length)];
var u=item.className;
$("."+u).fadeOut();
$("div[class='"+u+"'").show().fadeIn(1000);
}, 2000);
FIDDLE LINK: https://jsfiddle.net/bv0jj4wp/29/

Image change onclick using javascript is very fast?

Html and Javascript code:
<img src="imgs/right.gif" id="image_change" onclick="changeImage()"/>
<script>
function changeImage() {
var src = document.getElementById("image_change").src;
var imgsrc = src.substring(src.lastIndexOf("/")+1);
if (imgsrc == "left.gif")
{
document.getElementById("image_change").src = "imgs/right.gif";
alert('if'+document.getElementById("image_change").src);
}
else
{
document.getElementById("image_change").src = "imgs/left.gif";
alert('else'+document.getElementById("image_change").src);
}
}
</script>
When i click on the image, a new image is replacing in fraction of milli seconds..can i make the replacing of the image slow by using javascript or by adding any css class to it??any help would be appreciated..
try this
Using javascript
var op = 0.1; // initial opacity
element.style.display = 'block';
var timer = setInterval(function () {
if (op >= 1){
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
alert("here");
}, 10);
var img =document.getElementById("image_change");
fade(img);// Chnage image in fade method
Using jquery
// increase the 500 to larger values to increase the duration
// of the fadeout and/or fadein
$('#image_change').fadeOut(500, function () {
$('#image_change').attr("src", "/newImage.png");
$('#image_change').fadeIn(500);
});
The above jQuery way is straight forward and easy , if you want this in vanilla JavaScript you can use setTimeout with opacity to create fade out and fade in effect for further details check link below
Pure JavaScript fade in function
You can use setTimeout() function of window object to make delay for execution of your code.
Try this :
HTML :
<img src="http://www.hdwallpapers-3d.com/wp-content/uploads/2014/03/Cartoon-6.jpg" id="image_change" onclick="changeImage();" />
javaScript :
function changeImage() {
var src = document.getElementById("image_change").src;
var imgsrc = src.substring(src.lastIndexOf("/") + 1);
if (imgsrc == "Cartoon-6.jpg")
{
window.setTimeout(function(){
document.getElementById("image_change").src = "http://topwallpaperswide.com/wp-content/uploads/cartoon-wallpapers-jerry-the-mouse-running-and-shouting-20140823213658-53f9097a18af8.jpg";
//alert('if'+document.getElementById("image_change").src);
}, 1000);
}
else
{
window.setTimeout(function(){
document.getElementById("image_change").src = "http://www.hdwallpapers-3d.com/wp-content/uploads/2014/03/Cartoon-6.jpg";
//alert('else'+document.getElementById("image_change").src);
}, 1000);
}
}
jsFiddle
You can do it this way:
function changeImage() {
setTimeout(function() {
var src = document.getElementById("image_change").src;
if (src == "http://s25.postimg.org/iyly1k3uz/arrow_left.png") {
document.getElementById("image_change").src = "http://s25.postimg.org/tzh36kw3v/arrow_right.png";
} else {
document.getElementById("image_change").src = "http://s25.postimg.org/iyly1k3uz/arrow_left.png";
}
}, 1000);
}
body {
background-color: lightblue;
}
<img src="http://s25.postimg.org/tzh36kw3v/arrow_right.png" id="image_change" onclick="changeImage()" />

How to add slide animation for an image with JavaScript

I am trying to make a responsive image gallery in vanilla JS, I have a function and I am passing the image source as its parameter, and every time I am only changing the source on the click of next or previous button. Here is the function:
this.open = function (src) {
if (!src) {
return false;
}
for (count = 0; count <= imgSrc.length; count++) {
if (imgSrc[count] == src)
break;
var tempSrc = imgSrc[count];
}
imgRatio = false; // clear old image ratio for proper resize-values
var img = document.createElement('img');
img.setAttribute('src', src);
// hide overflow by default / if set
if (!this.opt || !isset(this.opt.hideOverflow) || this.opt.hideOverflow) {
body.setAttribute('style', 'overflow: hidden');
}
this.box.setAttribute('style', 'padding-top: 0');
this.wrapper.innerHTML = '';
this.wrapper.appendChild(img);
// console.log(this.wrapper.innerHTML);
addClass(this.box, 'jslghtbx-active');
// already show wrapper due to bug where dimensions are not
// correct in IE8
if (isIE8) {
addClass(that.wrapper, 'jslghtbx-active');
}
imgText.innerHTML = Details.static_data.gallery[count][3];
var checkClassInt = setInterval(function () {
if (hasClass(that.box, 'jslghtbx-active') && img.complete) {
// wait few ms to get correct image-dimensions
setTimeout(function () {
that.resize();
// add active-class for all other browsers
setTimeout(function () {
addClass(that.wrapper, 'jslghtbx-active');
}, 10);
clearInterval(checkClassInt);
}, 40);
}
}, 10); };
Is there any way so that I can attach animate kind of attribute to the image to have a sliding kind of animation. Please suggest your valuable feedback. [ NOTE: I am using this script https://github.com/felixhagspiel/jsOnlyLightbox ]

how to make hide/show text javascript smoother?

I am using this script to hide and show text however, I want to make the transition smoother but I am not sure how to. Here's a demo of it: http://jsfiddle.net/LnE5U/.
Please help me change it to make it smoother.
hide/show text
<div id="showOrHideDiv" style="display: none">hidden text</div>
<script language="javascript">
function showOrHide()
{
var div = document.getElementById("showOrHideDiv");
if (div.style.display == "block")
{
div.style.display = "none";
}
else
{
div.style.display = "block";
}
}
</script>
Here is an example using jQuery's fadeToggle (a shortcut for a more complicated animate)
// assuming jQuery
$(function () { // on document ready
var div = $('#showOrHideDiv'); // cache <div>
$('#action').click(function () { // on click on the `<a>`
div.fadeToggle(1000); // toggle div visibility over 1 second
});
});
HTML
<a id="action" href="#">hide/show text</a>
<div id="showOrHideDiv" style="display: none;">hidden text</div>
DEMO
An example of a pure JavaScript fader. It looks complicated because I wrote it to support changing direction and duration mid-fade. I'm sure there are still improvements that could be made to it, though.
function generateFader(elem) {
var t = null, goal, current = 0, inProgress = 0;
if (!elem || elem.nodeType !== 1) throw new TypeError('Expecting input of Element');
function visible(e) {
var s = window.getComputedStyle(e);
return +!(s.display === 'none' || s.opacity === '0');
}
function fader(duration) {
var step, aStep, fn, thisID = ++current, vis = visible(elem);
window.clearTimeout(t);
if (inProgress) goal = 1 - goal; // reverse direction if there is one running
else goal = 1 - vis; // else decide direction
if (goal) { // make sure visibility settings correct if hidden
if (!vis) elem.style.opacity = '0';
elem.style.display = 'block';
}
step = goal - +window.getComputedStyle(elem).opacity;
step = 20 * step / duration; // calculate how much to change by every 20ms
if (step >= 0) { // prevent rounding issues
if (step < 0.0001) step = 0.0001;
} else if (step > -0.0001) step = -0.0001;
aStep = Math.abs(step); // cache
fn = function () {
// console.log(step, goal, thisID, current); // debug here
var o = +window.getComputedStyle(elem).opacity;
if (thisID !== current) return;
if (Math.abs(goal - o) < aStep) { // finished
elem.style.opacity = goal;
if (!goal) elem.style.display = 'none';
inProgress = 0;
return;
}
elem.style.opacity = (o + step).toFixed(5);
t = window.setTimeout(fn, 20);
}
inProgress = 1; // mark started
fn(); // start
}
return fader;
}
And using it
window.addEventListener( // this section matches the code above
'load',
function () {
var fader = generateFader(document.getElementById('showOrHideDiv'));
document.getElementById('action').addEventListener(
'click',
function () {
fader(1000);
}
);
}
);
DEMO of this
This is quite simple. I have just made a demo and i used setInterval
Here's how it works
var fadeout = function( element ) { // 1
element.style.opacity = 1; // 2
window.setInterval(function() { // 3
if(element.style.opacity > 0) { // 4
element.style.opacity = parseFloat(element.style.opacity - 0.01).toFixed(2); // 5
} else {
element.style.display = 'none'; // 6
}
}, 50);
};
JSFiddle Demo Link
Steps
Create a function that accepts a DOM element
Set the opacity of the element to 1
Create a function that loops every 50ms
If the opacity is greater than 0 -> continue
Take away 0.01 from the opacity
if it's less than 0 the animation is complete and hide it completely
Note this is a really simple example and will need a bit of work
You can use somthing like this
$('.showOrHideDiv').toggle(function() {
$('showOrHideDiv').fadeIn('slow', function() {
//fadeIn or fadeOut, slow or fast, all the stuffs you want to trigger, "a function to execute every odd time the element is clicked," says the [jquery doc][1]
});
}, function() {
//here comes "additional handlers to cycle through after clicks," says the [jquery doc][1]
});
I used OPACITY to make it show/hide. See this Example, Full code (without jQuery):
Click here
<div id="MyMesage" style="display:none; background-color:pink; margin:0 0 0 100px;width:200px;">
blablabla
</div>
<script>
function ShowDiv(name){
//duration of transition (1000 miliseconds equals 1 second)
var duration = 1000;
// how many times should it should be changed in delay duration
var AmountOfActions=100;
var diiv= document.getElementById(name);
diiv.style.opacity = '0'; diiv.style.display = 'block'; var counte=0;
setInterval(function(){counte ++;
if ( counte<AmountOfActions) { diiv.style.opacity = counte/AmountOfActions;}
},
duration / AmountOfActions);
}
</script>
I followed iConnor solution and works fine but it had a small issue setInterval will not stop after the element be hidden I added stop interval to make it better performance
var fadeout = function( element ) { // 1
element.style.opacity = 1; // 2
let hidden_process = window.setInterval(function() { // 3
if(element.style.opacity > 0) { // 4
element.style.opacity = parseFloat(element.style.opacity - 0.01).toFixed(2); // 5
} else {
element.style.display = 'none'; // 6
console.log('1');
clearInterval(hidden_process);
}
}, 50);
};

JQuery Auto Click

I have a problem, I have 3 button lets say it's called #pos1, #pos2 and #pos3.
I want to makes it automatically click #pos1 button in 2 seconds, after that click the #pos2 after another 2 seconds, and #pos3 after another 2 seconds,
after that back to the #pos1 in another 2 seconds and so on via jQuery.
HTML
<button id="pos1">Pos1</button>
<button id="pos2">Pos2</button>
<button id="pos3">Pos3</button>
Anyone can help me please?
Try
$(function() {
var timeout;
var count = $('button[id^=pos]').length;
$('button[id^=pos]').click(function() {
var $this = $(this);
var id = $this.attr('id');
var next = parseInt(id.substring(4), 10) + 1;
if( next >= count ){
next = 1
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
$('#pos' + next).trigger('click');
}, 2000);
})
timeout = setTimeout(function() {
$('#pos1').trigger('click');
}, 2000);
})
var posArray = ["#pos1", "#pos2", "#pos3"];
var counter = 0;
setInterval(function() {
$(posArray[counter]).triggerHandler('click');
counter = ((counter<2) ? counter+1 : 0);
}, 2000);
That should do the trick, though you did not mention when you want it to stop running.
Well I don't know what you already have but technically it could be done via triggerHandler()
var currentPos = 1,
posCount = 3;
autoclick = function() {
$('#pos'+currentPos).triggerHandler('click');
currentPos++;
if(currentPos > posCount) { currentPos = 1; }
};
window.setInterval(autoclick,2000);
If I have understood you question right, you need to perform click in a continuous loop in the order pos1>pos2>pos3>pos1>pos2 and so on. If this is what you want, you can use jQuery window.setTimeout for this. Code will be something like this:
window.setTimeout(performClick, 2000);
var nextClick = 1;
function performClick() {
if(nextClick == 1)
{
$("#pos1").trigger("click");
nextClick = 2;
}
else if(nextClick==2)
{
$("#pos2").trigger("click");
nextClick = 3;
}
else if(nextClick == 3)
{
$("#pos3").trigger("click");
nextClick = 1;
}
window.setTimeout(performClick, 2000);
}
This is quite buggy but will solve your problem.
using setInterval()
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
var tempArray = ["pos1", "pos2", "pos3"]; //create an array to loop through
var arrayCounter = 0;
setInterval(function() {
$('#' + tempArray[arrayCounter ]).trigger('click');
arrayCounter = arrayCounter <2 ? arrayCounter +1 : 0;
}, 2000);
fiddle here
check your console for fiddle example

Categories

Resources