I'm using this flip plugin, see the code in this fiddle. The goal is to flip one box at a time, e.g. the second box clicked should revertFlip() the previous one. During the animation I don't want the other boxes to be clickable. I noted that the removeClass() is not working.
<div class='flippable'>I'm unflipped 1</div>
...
<div class='flippable'>I'm unflipped 9</div>
$('.flippable:not(.reverted)').live('click',function()
{
var $this = $(this);
var $prevFlip = $('.reverted');
var $allBoxes = $('.flippable');
$this.flip(
{
direction: 'lr',
color: '#82BD2E',
content: 'now flipped',
onBefore: function()
{
$prevFlip.revertFlip();
$prevFlip.removeClass('reverted');
},
onAnimation: function ()
{
$allBoxes.preventDefault();
},
onEnd: function()
{
$this.addClass('reverted');
}
})
return false;
});
I'll appreciate a lot your advise and suggestions.
Edit:
Error Console Output: $allBoxes.preventDefault is not a function
I believe this has something to do with revertFlip() calling onBefore and onEnd. This is causing some weirdness with addClass and removeClass. Check out my modified example: http://jsfiddle.net/andrewwhitaker/7cysr/.
You'll see if you open up FireBug that onBefore and onEnd are called multiple times, with I think is having the following effect (I haven't exactly worked out what's going on):
The call to onEnd for the normal "flip" sets reverted class for the desired element.
The call to onEnd for the "revert flip" action sets the same element as above again when onEnd is called.
Here's a workaround. I've taken out using onBegin and simplified onEnd since I'm not exactly sure what's going on with the revertFlip() call:
$(function() {
var handlerEnabled = true;
$('.flippable:not(.reverted)').live('click', function() {
if (handlerEnabled) {
var $this = $(this);
var $prevFlip = $('.reverted');
var $allBoxes = $('.flippable');
handlerEnabled = false;
$prevFlip.revertFlip();
$prevFlip.removeClass("reverted");
$this.addClass("reverted");
$this.flip({
direction: 'lr',
color: '#82BD2E',
content: 'now flipped',
onEnd: function() {
handlerEnabled = true;
}
});
}
return false;
});
})
I'm using a boolean flag to enable and disable the event listener. Try out this example: http://jsfiddle.net/andrewwhitaker/bX9pb/. It should work as you described in your OP (only flipping one over at a time).
Your original code ($allBoxes.preventDefault()) is invalid, because $allBoxes is a collection of elements. preventDefault is a function on the jQuery event object.
Can you try this script
var $prevFlip;
$('.flippable:not(.reverted)').live('click',function() {
var $this = $(this);
var $allBoxes = $('.flippable');
$this.flip( {
direction: 'lr',
color: '#82BD2E',
content: 'now flipped',
onBefore: function() {
if($prevFlip){
$prevFlip.revertFlip();
$prevFlip.removeClass('reverted');
}
},
onAnimation: function () {
//$allBoxes.preventDefault();
//This is not a valid line
},
onEnd: function() {
$this.addClass('reverted');
$prevFlip = $this;
}
});
return false;
});
This reverts only one previous item. This is not a complete solution. I think there are more problems to this. I'll post any further updates if I found them.
I think #Andrew got the answer you are looking for.
You can filter $this out of $allBoxes by using the not() method.
$allBoxes.not($this).revertFlip();
Related
I'm learning how to use objects to help organize my code and give it some structure but I've run into a problem. I don't understand how to set the $(this) from inside of one function to the $(this) of another function.
I'm researching call and apply but I can't seem to grasp how it works in this scenario.
cloneCard and clickCard is where I'm having the problem. I want to pass the $(this) that is referenced when I click the card to the cloneCard function.
Here is my code so far (updated to reflect the answer):
var Modal = {
init: function(config) {
this.config = config;
this.clickCard();
this.removeModal();
this.clickOutside();
this.createClose();
},
clickCard: function() {
$this = this;
this.config.boardOutput.on('click', '.card', function(event) {
$this.showOverlay();
$this.cloneCard.call($(this));
$this.createClose();
});
},
cloneCard: function() {
this.clone()
.replaceWith($('<div/>').html(this.html()))
.removeClass('card')
.addClass('modal')
.css("margin-top", $(window).scrollTop())
.prependTo('body');
},
showOverlay: function() {
this.config.overlay.show();
},
removeModal: function() {
$('.modal').remove();
$('.overlay').hide();
},
clickOutside: function() {
this.config.overlay.on('click', this.removeModal);
},
createClose: function() {
$('<span class="close">X</span>')
.prependTo('.modal')
.on('click', this.removeModal);
}
};
Modal.init({
boardOutput: $('#board-output'),
overlay: $('.overlay')
});
For what you need, calling self.cloneCard.call($(this)); instead of self.cloneCard($(this));
should work. What you're doing is, calling cloneCard passing it the element in which the the clickCard event occured.
If this doesn't work, i think we'll need more information to sovle your problem.
I'm new to javascript and jquery and I am trying to make a video's opacity change when I mouseover a li item. I know 'onmouseover' works because I have tested using the same jquery I use to scroll to the top of the page onclick.
The problem seems to be the syntax to check and update the style of the video div is not working. I adapted the code from a lesson on codeacademy and don't see why it work:
window.onload = function () {
// Get the array of the li elements
var vidlink = document.getElementsByClassName('video');
// Get the iframe
var framecss = document.getElementsByClassName('videoplayer1');
// Loop through LI ELEMENTS
for (var i = 0; i < vidlink.length; i++) {
// mouseover function:
vidlink[i].onmouseover = function () {
//this doesn't work:
if (framecss.style.opacity === "0.1") {
framecss.style.opacity = "0.5";
}
};
//onclick function to scroll to the top when clicked:
vidlink[i].onclick = function () {
$("html, body").animate({
scrollTop: 0
}, 600);
};
}
};
Here is a jsfiddle you can see the html and css:
http://jsfiddle.net/m00sh00/CsyJY/11/
It seems like such a simple problem so I'm sorry if I'm missing something obvious.
Any help is much appreciated
Try this:
vidlink[i].onmouseover = function () {
if (framecss[0].style.opacity === "0.1") {
framecss[0].style.opacity = "0.5";
}
};
Or alternatively:
var framecss = document.getElementsByClassName('videoplayer1')[0];
Or, better, give the iframe an id and use document.getElementById().
The getElementsByClassName() function returns a list, not a single element. The list doesn't have a style property. In your case you know the list should have one item in it, which you access via the [0] index.
Or, given that you are using jQuery, you could rewrite it something like this:
$(document).ready(function(){
// Get the iframe
var $framecss = $('.videoplayer1');
$('.video').on({
mouseover: function () {
if ($framecss.css('opacity') < 0.15) {
$framecss.css('opacity', 0.5);
}
},
click: function () {
$("html, body").animate({
scrollTop: 0
}, 600);
}
});
});
Note that I'm testing if the opacity is less than 0.15 because when I tried it out in your fiddle it was returned as 0.10000000149011612 rather than 0.1.
Also, note that the code in your fiddle didn't run, because by default jsfiddle puts your JS in an onload handler (this can be changed from the drop-down on the left) and you then wrapped your code in window.onload = as well. And you hadn't selected jQuery from the other drop-down so .animate() wouldn't work.
Here's an updated fiddle: http://jsfiddle.net/CsyJY/23/
I've already posted a question about jQuery toggle method here
But the problem is that even with the migrate plugin it does not work.
I want to write a script that will switch between five classes (0 -> 1 -> 2 -> 3 -> 4 -> 5).
Here is the part of the JS code I use:
$('div.priority#priority'+id).on('click', function() {
$(this).removeClass('priority').addClass('priority-low');
});
$('div.priority-low#priority'+id).on('click' ,function() {
$(this).removeClass('priority-low').addClass('priority-medium');
});
$('div.priority-medium#priority'+id).on('click', function() {
$(this).removeClass('priority-medium').addClass('priority-normal');
});
$('div.priority-normal#priority'+id).on('click', function() {
$(this).removeClass('priority-normal').addClass('priority-high');
});
$('div.priority-high'+id).on('click', function() {
$(this).removeClass('priority-high').addClass('priority-emergency');
});
$('div.priority-emergency'+id).on('click', function() {
$(this).removeClass('priority-emergency').addClass('priority-low');
});
This is not the first version of the code - I already tried some other things, like:
$('div.priority#priority'+id).toggle(function() {
$(this).attr('class', 'priority-low');
}, function() {
$(this).attr('class', 'priority-medium');
}, function() {
...)
But this time it only toggles between the first one and the last one elements.
This is where my project is: strasbourgmeetings.org/todo
The thing is that your code will hook your handlers to the elements with those classes when your code runs. The same handlers remain attached when you change the classes on the elements.
You can use a single handler and then check which class the element has when the click occurs:
$('div#priority'+id).on('click', function() {
var $this = $(this);
if ($this.hasClass('priority')) {
$this.removeClass('priority').addClass('priority-low');
}
else if (this.hasClass('priority-low')) {
$this.removeClass('priority-low').addClass('priority-medium');
}
else /* ...and so on... */
});
You can also do it with a map:
var nextPriorities = {
"priority": "priority-low",
"priority-low": "priority-medium",
//...and so on...
"priority-emergency": "priority"
};
$('div#priority'+id).on('click', function() {
var $this = $(this),
match = /\bpriority(?:-\w+)?\b/.exec(this.className),
current = match && match[0],
next = nextPriorities[current];
if (current) {
$this.removeClass(current).addClass(next || 'priority');
}
});
[edit: working demo]
Assuming you have 'priority' as the default class already on the element at the initialization phase, this will cycle through the others:
$('div#priority' + id)
.data('classes.cycle', [
'priority',
'priority-low',
'priority-medium',
'priority-normal',
'priority-high',
'priority-emergency'
])
.data('classes.current', 0)
.on('click', function () {
var $this = $(this),
cycle = $this.data('classes.cycle'),
current = $this.data('classes.current');
$this
.removeClass(cycle[current % cycle.length])
.data('classes.current', ++current)
.addClass(cycle[current % cycle.length]);
});
I have tried myself to do this with the sole help of toggleClass() and didn't succeeded.
Try my method that declares an array with your five classes and toggles dynamically through
them.Do adapt to your own names.
//variable for the classes array
var classes=["one","two","three","four","five"];
//add a counter data to your divs to have a counter for the array
$('div#priority').data("counter",0);
$(document).on('click','div#priority',function(){
var $this=$(this);
//the current counter that is stored
var count=$this.data("counter");
//remove the previous class if is there
if(($this).hasClass(classes[count-1])){
$(this).removeClass(classes[count-1]));
}
//check if we've reached the end of the array so to restart from the first class.
//Note:remove the comment on return statement if you want to see the default class applied.
if(count===classes.length){
$this.data("counter",0);
//return;//with return the next line is out of reach so class[0] wont be added
}
$(this).addClass(classes[count++]);
//udpate the counter data
$this.data("counter",count);
});
//If you use toggleClass() instead of addClass() you will toggle off your other classes.Hope is a good answer.
I'm trying to fade out a div on a click but also change some css values.
the issue im having is that the values change while the fade out is happening (too early). I need the values to change once the fade out has finished:
<script type="text/javascript">
$('#r_text').click(function() {
$(".box1_d").fadeOut();
$(".box1_c").css("top","0px");
});
</script>
Now when i run that, everything works but just not exactly how i'd like it.. I need the css values to be changed once the fadeout has finished, not while it's still happening.
is this possible?
if so, any ideas how?
thank you.
Use a callback function to modify the .css() as the second parameter to fadeOut(). It will fire when the fade completes.
<script type="text/javascript">
var fadeTime = 500;
$('#r_text').click(function() {
$(".box1_d").fadeOut(fadeTime, function() {
$(".box1_c").css("top","0px");
});
});
</script>
Provided you use jQuery version >= 1.5, you can/should utilize the Deferred object instead of using the callback parameter:
$('#r_text').click((function () {
var animations = {
initial: function () {
return $(".box1_d").fadeOut(1500);
},
following: function () {
return $(".box1_c").css("top","0px").animate({fontSize: '150%'});
},
onDone: function () {
alert('DONE!');
}
};
return function(e) {
$.when(animations.initial())
.pipe(animations.following)
.done(animations.onDone);
e.preventDefault();
};
}()));
JsFiddle of it in action: http://jsfiddle.net/wGcgS/2/
I am trying to delay the default event or events in a jQuery script. The context is that I want to display a message to users when they perform certain actions (click primarily) for a few seconds before the default action fires.
Pseudo-code:
- User clicks link/button/element
- User gets a popup message stating 'You are leaving site'
- Message remains on screen for X milliseconds
- Default action (can be other than href link too) fires
So far, my attempts look like this:
$(document).ready(function() {
var orgE = $("a").click();
$("a").click(function(event) {
var orgEvent = event;
event.preventDefault();
// Do stuff
doStuff(this);
setTimeout(function() {
// Hide message
hideMessage();
$(this).trigger(orgEvent);
}, 1000);
});
});
Of course, this doesn't work as expected, but may show what I'm trying to do.
I am unable to use plugins as ths is a hosted environment with no online access.
Any ideas?
I would probably do something like this.
$("a").click(function(event) {
event.preventDefault();
doStuff(this);
var url = $(this).attr("href");
setTimeout(function() {
hideMessage();
window.location = url;
}, 1000);
});
I'm not sure if url can be seen from inside the timed function. If not, you may need to declare it outside the click handler.
Edit: If you need to trigger the event from the timed function, you could use something similar to what karim79 suggested, although I'd make a few changes.
$(document).ready(function() {
var slept = false;
$("a").click(function(event) {
if(!slept) {
event.preventDefault();
doStuff(this);
var $element = $(this);
// allows us to access this object from inside the function
setTimeout(function() {
hideMessage();
slept = true;
$element.click(); //triggers the click event with slept = true
}, 1000);
// if we triggered the click event here, it would loop through
// this function recursively until slept was false. we don't want that.
} else {
slept = false; //re-initialize
}
});
});
Edit: After some testing and research, I'm not sure that it's actually possible to trigger the original click event of an <a> element. It appears to be possible for any element other than <a>.
Something like this should do the trick. Add a new class (presumably with a more sensible name than the one I've chosen) to all the links you want to be affected. Remove that class when you've shown your popup, so when you call .click() again your code will no longer run, and the default behavior will occur.
$("a").addClass("fancy-schmancy-popup-thing-not-yet-shown").click(function() {
if ($(this).hasClass("fancy-schmancy-popup-thing-not-yet-shown"))
return true;
doStuff();
$(this).removeClass("fancy-schmancy-popup-thing-not-yet-shown");
var link = this;
setTimeout(function() {
hideMessage();
$(link).click().addClass("fancy-schmancy-popup-thing-not-yet-shown";
}, 1000);
return false;
});
Probably the best way to do this is to use unbind. Something like:
$(document).ready(function() {
$("a").click(function(event) {
event.preventDefault();
// Do stuff
this.unbind(event).click();
});
})
This might work:
$(document).ready(function() {
$("a").click(function(event) {
event.preventDefault();
doStuff(this);
setTimeout(function() {
hideMessage();
$(this).click();
}, 1000);
});
});
Note: totally untested