Normally my slideshow goes automatically to the next picture, but I want to detect if it goes backwards by an user-initiated action (keyboard arrows or controls). My solution to this would be to do this (my imaginary code):
if(jQuery("#slideshow article").hasChangedClassFrom("previous").hasChangedClassTo("current")) {
backwards = true;
}
if(backwards) { // code for backwards
jQuery("#slideshow article.previous").css("z-index", "1");
jQuery("#slideshow article.next").css("z-index", "2");
}
else { // code for forwards (normal state)
jQuery("#slideshow article.previous").css("z-index", "2");
jQuery("#slideshow article.next").css("z-index", "1");
}
The classes are already implemented, so that the current slide always has the class "current" and so on. I know this isn't valid code at all, but by reading this, I think it would be quite clear what I want to achieve. I'm not very good at JavaScript/jQuery, but I've tried searching for solutions like this without luck.
Live site // Live JS code
Based on the code from the mentioned link http://dans.no/cycle.js
Declare a variable clickindex=0;
Place the following inside the click function of jQuery("#slideshow nav a").click
clickindex = jQuery("#slideshow nav a").index(this);
if(clickindex<index){
console.log("execute some logic");
}
The jsfiddle link for my solution javascript code http://jsfiddle.net/y601tkfL/
Instead of guessing that the previous class, use the current and the previous index.
http://jsfiddle.net/whyba4L9/5/
UPDATE 2:
var stopp, antall = jQuery("#slideshow article").length;
var index = 0
function slideTo(idx) {
jQuery("#slideshow article, #slideshow nav a").removeAttr("class").filter(':nth-of-type(' + (idx+1) + ')').addClass("current");
if(jQuery("#slideshow article:nth-of-type(2)").hasClass("current")) {
jQuery("#slideshow article:first-of-type").addClass("forrige");
jQuery("#slideshow article:last-of-type").addClass("neste");
}
else if(jQuery("#slideshow article:first-of-type").hasClass("current")) {
jQuery("#slideshow article:last-of-type").addClass("forrige");
jQuery("#slideshow article:nth-of-type(2)").addClass("neste");
}
else if(jQuery("#slideshow article:last-of-type").hasClass("current")) {
jQuery("#slideshow article:nth-of-type(2)").addClass("forrige");
jQuery("#slideshow article:first-of-type").addClass("neste");
}
if(index ==antall-1 && idx ==0 )
{
//lasto to first
}
else if(index>idx || (index == 0 && idx == antall-1))
{
alert('BACKWARDS')
}
index = idx;
};
function startCycle() {
stopp = setInterval(function() {
jQuery("#slideshow article").stop(true, true);
var idx = index + 1 > antall - 1 ? 0 : index + 1;
slideTo(idx,false);
}, 5500);
};
if (antall > 1) {
jQuery("#slideshow").append("<nav>").css("height", jQuery("#slideshow img").height());
jQuery("#slideshow article").each(function() {
jQuery("#slideshow nav").append("<a>•</a>");
}).filter(":first-of-type").addClass("current first");
jQuery("#slideshow article:nth-of-type(2)").addClass("neste");
jQuery("#slideshow article:last-of-type").addClass("forrige");
startCycle();
jQuery("#slideshow nav a").click(function() {
clearInterval(stopp);
startCycle();
var idx = jQuery("#slideshow nav a").index(this);
if (index === idx) return;
slideTo(idx);
}).filter(":first-of-type").addClass("current");
jQuery(document).keyup(function(e) {
if (e.keyCode == 37) {
var idx = index - 1 < 0 ? antall - 1 : index - 1;
slideTo(idx);
clearInterval(stopp);
startCycle();
}
else if (e.keyCode == 39) {
var idx = index + 1 > antall - 1 ? 0 : index + 1;
slideTo(idx);
clearInterval(stopp);
startCycle();
}
});
}
Try calling this function when the user changes the image with parameter of this. I hope I correctly understood what you are asking. If not let me know and I will recode it. Also if the slide show is finished please post your html and javascript.
function whatever(this)
{
if(this.className == 'previous')
{
alert('the user has changed the image');
this.className = 'current';
}
else
{
alert('the user hasn\'t changed the image');
}
}
The dead simplest way to do this, from what I understand your question to aim at, is to put a handler on the index buttons and a method for tracking the current image.
Listen for slide change
var currentSlide = '';
$('.slideIndexButtons').on('click', function(e){
// Conditional logic that compares $(this).data('whichimage') to currentSlide
var whichImage = $(this).data('whichimage');
// ->this means attaching data-whichimage="" to each of the elements, or
// ->you can just stick with detecting the class and going from there
// Either process results in isBackwards boolean
if (currentSlide == 'prev' && whichImage == 'current') {
isBackwards = true;
}
if (isBackwards) {
// Backwards logic here
} else {
// Other logic here
}
// Unless the event we're listening for in keeping currentSlide updated is also fired when
// the slide changes due to user input, we'll need to update currentSlide manually.
currentSlide = whichImage;
});
Track the current slide
$('#slider').on('event', function(){
// This is assuming that we're strictly listening to the slider's automatic sliding
// The event you attach this to is either fired before or after the slide changes.
// Knowing which is key in getting the data you want. You are either getting
// The data from this slide $(this).data('whichimage') or
// $(this).next().data('whichimage')
// Again, you can go with classes, but it is a lot of logic which you have to
// update manually if you ever have to add or alter an image in the slide set.
// Either way, you end up with the variable targetImage
currentSlide = targetImage;
});
With any luck, your slideshow code has an API that will allow you to listen for when slide-related events are fired. Otherwise, you'll have to find a way of setting up, firing and listening for these events manually, either through callbacks passed in or by (eek!) altering the code and possibly unintentionally changing its functionality.
This should give you what you asked for. Let me know how it goes.
You can add this line at the very start of slideTo function in your cycle.js
if((idx < index && !(idx == 0 && index == antall - 1)) ||
(idx == antall - 1 && index == 0)){
jQuery.trigger('BACKWARDS')
}
and then add an event handler for "BACKWARDS" somewhere else convenient (Maybe at the end of cycle.js?).
jQuery.on('BACKWARDS', function(e){
//DO THINGS HERE
}
I wrote a plugin attrchange which I think will effectively solve your problem. attrchange is a simple jQuery plugin to detect an attribute change. The plugin internally uses one of the following compatible methods based on the browser to detect an attribute change,
Mutation Observer
DOMAttrModified
onpropertychange
Try out below demo to understand more about how you can use the plugin for your need.
Click to read more about attrchange.
Note: The plugin doesn't use polling so you can use it without any worries, however polling is supported as an extension to the plugin. You can read more if you are interested.
$('#test').one('click', function() {
$('#test').attrchange({
trackValues: true,
callback: function(event) {
$('#result').html('<div><label>Attribute Name: </label>' + event.attributeName + '</div>' + '<div><label>Old Value</label>' + event.oldValue + '</div>' + '<div><label>New Value</label>' + event.newValue + '</div>');
}
});
//this will toggleClass 'blue-background' every 2 secs
setInterval(function() {
$('#test').toggleClass('lightblue-background');
}, 2000);
});
html {
font-family: Segoe UI, Arial, sans-serif;
font-size: 13px;
}
div#test {
border: 1px solid #d2d2d2;
padding: 10px;
display: inline-block;
}
.lightblue-background {
background-color: #DBEAF9;
}
div label {
font-weight: bold;
margin-right: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/meetselva/attrchange/master/js/attrchange.js"></script>
<div id="test">
<p style="font-weight: bold;">Click anywhere in this box to Start the DEMO</p>
<p>The demo is to simply toggle a class 'lightblue-background' to this div every 2 secs.</p>
<div id="result" style="font-size: 0.9em;"></div>
See the pseudo code for your case using the plugin,
jQuery("#slideshow article").attrchange({
trackValues: true,
callback: function(event) {
if ($(this).hasClass('current') &&
(event.oldValue && event.oldValue.indexOf('previous') >= 0)) {
//code for backward
} else {
//code for forward
}
}
});
Related
I am doing some easy div filtering with jQuery and input field. It is working, however it is not detecting that it is empty if I remove input using " Ctrl + a + backspace ", in other words if I select all text and remove it. What causes this?
It is not reordering divs back to default if using the keyboard commands but is going back to normal if you backspace every character.
This is how I do it:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
$('.card').show();
} else {
$('.card').each(function() {
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
});
};
});
Your if block that handles the empty string is not showing the same elements that the else block hides. The else block calls .parent() but the if block does not.
So the else case shows or hides the parent of each .card element, but the if case shows the .card elements themselves—without unhiding their parents. See my comments added to the code (I also reformatted the conditional expression in the else for clarity):
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
// Show all of the .card elements
$('.card').show();
} else {
$('.card').each(function() {
var text = $(this).text().toLowerCase();
// Show or hide the *parent* of this .card element
text.indexOf(valThis) >= 0 ?
$(this).parent().show() :
$(this).parent().hide();
});
};
});
Since it sounds like the non-empty-string case is working correctly, it should just be a matter of adding .parent() in the if block so it matches the others:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
// Show the parent of each .card element
$('.card').parent().show();
} else {
// Show or hide the parent of each .card element
$('.card').each(function() {
var text = $(this).text().toLowerCase();
text.indexOf(valThis) >= 0 ?
$(this).parent().show() :
$(this).parent().hide();
});
};
});
This is the kind of situation where familiarity with your browser's debugging tools would pay off big time. The .show() or .hide() methods manipulate the DOM, and by using the DOM inspector you could easily see which elements are being hidden and shown.
In fact, as a learning exercise I recommend un-fixing the bug temporarily by going back to your original code, and then open the DOM inspector and see how it reveals the problem. While you're there, also try out the JavaScript debugger and other tools.
If you use Chrome, here's an introduction to the Chrome Developer Tools. Other browsers have similar tools and documentation for them.
It seems to be working just fine:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
$('.card').show();
console.log("input is empty");
} else {
console.log("input is not empty");
$('.card').each(function() {
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="brandSearch">
See the JSFiddle here: http://jsfiddle.net/jL6d2qp6/
I have an animation that is supposed to keep the #top element in a fixed position at the top of the page, except for when the #login element is on the screen. To control this, I am using a javascript function that runs every 10ms and switches out the css class for #top, and when I scroll down, it updates as expected, but when I try to scroll back up, nothing happens.
javascript code in question:
offScreen = function(id, targetValue)
{
var offset = $("#top").offset();
var w = $(window);
var height = $(id).innerHeight();
var finalOffset = (offset.top + height) - w.scrollTop();
if (finalOffset < targetValue)
{
return true;
}
else
{
return false;
}
}
function updateTopMenu()
{
if (offScreen("#login", 81) === false)
{
if($("#top").hasClass("top-bar-absolute") === false)
{
$("#top").addClass("top-bar-absolute");
console.log("added top-bar-absolute");
}
if($("#top").hasClass("top-bar-fixed") === true)
{
$("#top").removeClass("top-bar-fixed");
console.log("removed top-bar-fixed");
}
}
if(offScreen("#login", 81) === true)
{
if($("#top").hasClass("top-bar-absolute") === true)
{
$("#top").removeClass("top-bar-absolute");
console.log("removed top-bar-absolute");
}
if($("#top").hasClass("top-bar-fixed") === false)
{
$("#top").addClass("top-bar-fixed");
console.log("added top-bar-fixed");
}
}
}
$("#top").ready( function() {
setInterval(updateTopMenu, 10);
});
Also, if there is a better way to accomplish this, I'd like it because this feels kind of cheaty.
The easiest way to achieve this is listening to the scroll event on the window. This is called every time the user scrolls. Then you can check whether the user scrolled past the login box, i.e. beyond the login box's height.
If the login box is no longer in the window, assign the #top box a class like .sticky that will change its position to position: fixed. And otherwise remove this class.
Checkout this jsFiddle.
I'm using a slideshow on my website using jquery Cycle 1.
I navigate into my slideshow with #next function. when clicking on my last slide of my slideshow it redirect me to another page (var random_next_url_enfant).
I would like to add the spacebar and the right arrow key to navigation inside my slideshow.
when I add this Js code it works, but on the last slide it starts the slideshow again instead of redirecting me to the next page.
$(document.documentElement).keyup(function (e) {
if (e.keyCode == 39)
{
$('#slider_projets').cycle('next');
}
});
here is my full code using the mouse click. on the last slide, it redirects me to another page, it works perfectly. but I would like to get the same with the spacebar and the right arrow :
$('#slider_projets').cycle({
speed: 600, //temps d'animation
timeout: 0, //fréquence
fx: 'scrollLeft',
//compteur//
pager: "#nav",
after: function(currSlideElement, nextSlideElement, options, forwardFlag) {
$('#counter_1').text((options.currSlide + 1) + ' / ' + (options.slideCount));
slideIndex = options.currSlide;
nextIndex = slideIndex + 1;
prevIndex = slideIndex - 1;
if (slideIndex == options.slideCount - 1) {
/*nextIndex = 0;*/
var random_next_url_enfant = $("#random_next_url_enfant").val();
$('#next').on("click", function(e){
e.preventDefault();
window.location = random_next_url_enfant;
});
}
if (slideIndex === 0) {
prevIndex = options.slideCount - 1;
}
}
});
I think i'm missing something but I can't find what !
here is a jsfiddle :
http://jsfiddle.net/8HsdG/
thanks a lot for your help,
You need access to your slider options outside of your slider, the reason you are not getting to the url is because there is no listener telling it to go there, only the click event.
Here is a jsfiddle that will get you very close, it has everything you need, you just have to fill in the blanks.
http://jsfiddle.net/kkemple/8HsdG/1/
I wrapped your code in an anonymous function so I could declare some scoped variables
(function () {
var slideIndex, slideCount;
// all of your code is here
})();
I then added a before call on your slider:
before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
slideCount = options.slideCount;
},
then added the following code to your key events:
if ( slideIndex == slideCount ) {
//redirect to random url
e.preventDefault;
}
#kkemple, I've resolved the problem... I just had to change :
$(document.documentElement).keyup(function (e) {
if (e.keyCode == 32)
{
$('#slider_projets').cycle('next');
}
});
by
$(document.documentElement).keyup(function (e) {
if (e.keyCode == 32)
{
$("#next").trigger("click");
}
});
and it works perfectly ! anyway thanks for your help !
I'm currently using the below code to colour the cells based on their value:
cell.each(function() {
var cell_value = $(this).html();
if (cell_value == 0){
$(this).css({'background' : '#DF0101'});
} else if ((cell_value >= 1) && (cell_value <=10)) {
$(this).css({'background' : '#FF7C00'});
} else if (cell_value >= 8) {
$(this).css({'background' : '#04B404'});
}
});
I've also added the CSS to the stylesheet:
td:hover{
background-color:#CA2161;}
So how can I make it so that on hover the cells processed in the javascript will change colour? At the minute they won't change at all, they just stay as the colour processed above^^^
Just try to bind an hover function to the "tds" of your table like this
$('td').hover(function(){
$(this).css('background-color', '#CA2161');
});
and if you want to remove the colour on mouse out you can try this
$( "td" ).hover(
function() {
$(this).css('background-color', '#CA2161');
}, function() {
$(this).css('background-color', '');
}
);
EDIT: Turns out you want the colors to leave instead of show when you hover. Simple change.
Okay first of all, you should separate these out into CSS classes:
.ZeroValue {
background:'#DF0101';
}
.ValueBetween1And10 {
background:'#FF7C00';
}
.ValueOver8 {
background:'#04B404';
}
.ValueTransparent {
background:transparent !important;
}
Add the above classes on $(document).ready() based on their values:
if(cell_value === 0){
cell.addCLass('ZeroValue');
} else if((cell_value >= 1) && (cell_value <= 10)){
cell.addClass('ValueBetween1And10');
} else if(cell_value >= 8){
cell.addClass('ValueOver8');
}
Then just dynamically add the transparent class when you hover, removing it when you leave:
cell.on({
mouseenter:function(){
$(this).addClass('ValueTransparent');
},
mouseleave:function(){
$(this).removeClass('ValueTransparent');
}
});
Or if there was a unique color to each item and you wanted to temporarily remove that, you would just create a function:
function classByValue(cell,cell_value){
if(cell_value === 0){
cell.addCLass('ZeroValue');
} else if((cell_value >= 1) && (cell_value <= 10)){
cell.addClass('ValueBetween1And10');
} else if(cell_value >= 8){
cell.addClass('ValueOver8');
}
}
This will clear any of the classes when the mouse enters, and then re-add the class based on cell_value when mouse enters. Then dynamically apply on load and when mouseleave. The $(document).ready():
cell.each(function(){
classByValue(this,this.val());
});
And the hover:
cell.on({
mouseenter:function(){
$(this).removeClass('ZeroValue ValueBetween1And10 ValueOver8');
},
mouseleave:function(){
classByValue($(this),$(this).val());
}
});
There you have it, multiple ways to accomplish your goal. You might need to modify $(this).val() to appropriately reflect the value of that specific cell, but without your HTML I can't really determine that.
As a side, that last option with >= 8 should probably be reconsidered, because a value of 8 or 9 will never fire it.
I have this wizard step form that I simulated with <ul> list items by overlapping inactive <li> items with absolute positioning.
The wizard form is working as desired except that I want to hide next or previous button on a certain step.
This is my logic in jQuery but it doesn't do any good.
if (index === 0) {
$('#prev').addClass(invisible);
$('#prev').removeClass(visible);
} else if (index === 1) {
$('#prev').addClass(visible);
$('#prev').removeClass(invisible);
} else {
$('#next').addClass(invisible);
}
To get the index value I used eq() chained on a current step element like the following
var current;
var index = 0;
$(function () {
current = $('.pg-wrapper').find('.current');
$('#next').on('click', function() {
if (current.next().length===0) return;
current.next().addClass('current').show();
current.removeClass('current').hide();
navstep.next().addClass('active');
navstep.removeClass('active');
current = current.next();
navstep = navstep.next();
index = current.eq();
});
I tried to isolate it as much as possible but my full code will give you a better idea.
If you would care to assist please check my JS BIN
There were several issues
you used .eq instead of index
you were missing quotes around the class names
your navigation logic was flawed
no need to have two classes to change visibility
I believe the following is an improvement, but let me know if you have questions.
I added class="navBut" to the prev/next and rewrote the setting of the visibility
Live Demo
var current;
var navstep;
$(function () {
current = $('.pg-wrapper').find('.current');
navstep=$('.nav-step').find('.active');
$('.pg-wrapper div').not(current).hide();
setBut(current);
$('.navBut').on('click', function() {
var next = this.id=="next";
if (next) {
if (current.next().length===0) return;
current.next().addClass('current').show();
navstep.next().addClass('active');
}
else {
if (current.prev().length===0) return;
current.prev().addClass('current').show();
navstep.prev().addClass('active');
}
current.removeClass('current').hide();
navstep.removeClass('active');
current = (next)?current.next():current.prev();
navstep = (next)?navstep.next():navstep.prev();
setBut(current);
});
});
function setBut(current) {
var index=current.index();
var max = current.parent().children().length-1;
$('#prev').toggleClass("invisible",index<1);
$('#next').toggleClass("invisible",index>=max);
}
The eq function will not give you the index, for that you need to use the index() function.
I have not looked at the whole code but shouldn't your class assignemnts look like:
$('#prev').addClass('invisible');
$('#prev').removeClass('visible');
i.e. with quotes around the class names? And is it really necessary to have a class visible? Assigning and removing the class invisible should easily do the job (provided the right styles have been set for this class).
You should make 4 modifications.
1) Use .index() instead of .eq();
2) Add a function changeIndex which changes the class depends on the index and call it on click of prev and next.
3) add quotes to invisible and visible
4) There is a bug in your logic, try going to 3rd step and come back to 1st step. Both buttons will disappear. So you have to make next button visible if index = 0
Here is the demo :
http://jsfiddle.net/ChaitanyaMunipalle/9SzWB/
Use index() function instead of eq() because eq() will return object and index() will return the integer value.
DEMO HERE
var current;
var navstep;
var index = 0;
$(function () {
current = $('.pg-wrapper').find('.current');
navstep=$('.nav-step').find('.active');
$('.pg-wrapper div').not(current).hide();
}(jQuery));
$('#next').on('click', function() {
if (current.next().length===0) return;
current.next().addClass('current').show();
current.removeClass('current').hide();
navstep.next().addClass('active');
navstep.removeClass('active');
current = current.next();
navstep = navstep.next();
index = current.index();
change_step(index)
});
$('#prev').on('click', function() {
if (current.prev().length===0) return;
current.prev().addClass('current').show();
current.removeClass('current').hide();
navstep.prev().addClass('active');
navstep.removeClass('active');
current = current.prev();
navstep = navstep.prev();
index = current.index();
change_step(index)
});
function change_step(value)
{
if (value === 0) {
$('#prev').hide();
$('#next').show();
} else if (value === 1) {
$('#prev').show();
$('#next').show();
} else {
$('#next').hide();
$('#prev').show();
}
}