I'm trying to add a playpause button to my flexslider presentation. Instead of the standard playpause button (inside the presentation) I would like to add a separate button somewhere else on the html-page.
Unfortunately I'm no expert in javascript. I can't seem to figure out how to make an element (say an image) somewhere else on my page behave like the play-pause button. How to connect it to the right script?
And if this is simply too difficult, just a play-button would also do... since the presentation pauses automatically when the visitors click next or previous.
Hope anybody can help us out! Thanks
Create one button,
<input type='button' value='START SLIDESHOW' id='play-gallery' />
Then write js code for it,
put code in flexslide's function,
$('.flexslider').flexslider({
animation: "slide",
controlNav: false,
pausePlay: false,
slideshowSpeed: 4000,
slideToStart: 0,
start: function(slider) {
var slideshowPlaying = true;
$('#play-gallery').click(function() {
if($('ul.slides li').length > 1) {
if (slideshowPlaying == true) {
slideshowPlaying = false;
slider.pause();
$('#play-gallery').html('START SLIDESHOW');
} else {
slideshowPlaying = true;
slider.flexAnimate(slider.getTarget("next"));
slider.play();
$('#play-gallery').html('STOP SLIDESHOW');
}
}
});
}
});
#HB Kautil +1 for your answer. But I had to change just two parts of your code. Would've added this as a comment but my "reputation" isn't there yet.
$('#play-gallery').val('START SLIDESHOW');
And
$('#play-gallery').val('STOP SLIDESHOW');
Other than that your answer did all the heavy lifting :)
Related
I am using pretty photo jquery plugin to display slide show, last slide is 'Enter site', when user click on this slide, slide show should stop and user will be redirected to home page of website. How can I implement this.
I tried to use onclick event of and tag but none of them are getting called. I even tried to register onclick event from jQuery using 'on' function but no luck.
Thanks in advance.
Since the callback function is called when prettyPhoto is closed, you need to use:
changepicturecallback, which is called everytime an item is shown/changed.
In this function you have to read the current item and evaluate if it's the last one.
Try this piece of code:
$("a[rel^='prettyPhoto']").prettyPhoto({
animationSpeed:'normal',
slideshow:5000,
show_title: true,
allow_resize: true,
autoplay_slideshow: true,
social_tools: false,
deeplinking: false,
callback: function(){
console.log('pretty photo is closed')
},
image_markup: '<img id="fullResImage" class="fullResImage" src="{path}" />',
changepicturecallback: function(){
var currentSlide = ($('.pp_gallery').find('li').index($('.selected'))+1);
var myArray = jQuery('.currentTextHolder').text().split('/');
if(currentSlide == myArray[1]){
/* Make redirect to your HP */
}
}
});
I want to produce a manual tooltip based upon some user input. The easiest way was to hide all tooltips and then show the relevent ones.
I've reduced my code down to the bare essentials, and my tooltip keeps disappearing after the second "show".
I'm using bootstrap 3.3.4 and jquery 2.1.3
Is there a problem with doing a show immediatly after a hide or am I missing something in my code?
<input id="check" type="checkbox">
<script>
var toolTipData = {
placement: 'right',
title: 'Checkmark checked',
trigger: "manual"
};
$('#check').tooltip(toolTipData);
$(document).on('change', '#check', function () {
$('#check').tooltip("hide");
if (document.getElementById("check").checked) {
$('#check').tooltip("show");
}
});
</script>
Here's a jsfiddle: https://jsfiddle.net/bbrally/4b9g0abh/
You're experiencing a race condition between when the "hide" event happens and when the "show" event happens. Per the documentation the "hide/show" events actually return to the caller before the "hidden/shown" events fire.
http://getbootstrap.com/javascript/#tooltips
Scroll down to the "Methods" section under tooltips
...Returns to the caller before the tooltip has actually been hidden...
...Returns to the caller before the tooltip has actually been shown...
I'm not suggesting the code below is a solution (though, it might be good enough?), but an explanation as to what you're running into. Specifically the timeout value of 250ms will slow it down enough such that it works as you're intending.
var toolTipData = {
placement: 'right',
title: 'Checkmark checked',
trigger: "manual"
};
$('#check').tooltip(toolTipData);
$(document).on('change', '#check', function () {
$('#check').tooltip("hide");
if (document.getElementById("check").checked) {
setTimeout(function() {
$('#check').tooltip("show");
}, 250);
}
});
Hope this helps.
$(document).on('change', '#check', function () {
if (document.getElementById("check").checked) {
$('#check').tooltip("show");
}
else{
$('#check').tooltip("hide");
}
});
It was trying to hide, even though it shouldn't, separate both cases.
I want to toggle functions using the jQuery waypoint function, how can I combine these pieces of code to make that happen? (I would be happy with alternative solutions too).
I want to combine this.....
$('#pageborder').waypoint(function(direction) {
//do something here
}, { offset: 'bottom-in-view' });
With this......
.toggle(function(){
$('.play', this).removeClass('pausing');
$('.play', this).addClass('playing');
}, function(){
$('.play', this).addClass('pausing');
$('.play', this).removeClass('playing');
});
The end result should be functions getting toggled when the way point is reached.
More info on the JQuery Waypoint plugin here: http://imakewebthings.com/jquery-waypoints/#doc-waypoint
Here is an example of using the waypoint plugin to do something when the waypoint is reached. In my example I am showing and hiding something based on if the user is scrolling up or down:
Demo: http://jsfiddle.net/lucuma/pTjta/
$(document).ready(function () {
$('.container div:eq(1)').waypoint(function (direction) {
if (direction == 'down') $('.toggleme').show();
else {
$('.toggleme').hide();
}
}, {
offset: $.waypoints('viewportHeight') / 2
});
});
E.B.D., I see you have something working.
If you wanted a slightly more concise toggle action, then you might consider the following :
var $next_btn_containers = $('.next_btn_container, .next_btn_container_static');
$('#pageborder').waypoint(function(dir) {
$next_btn_containers
.toggleClass('next_btn_container_static', dir == 'down')
.toggleClass('next_btn_container', dir == 'up');
}, { offset: 'bottom-in-view' });
By pre-selecting and remembering all members of both classes, execution will be faster - particularly in a large DOM.
The original selector may well simplify, depending on how the elements are initialized.
With a little more thought (and appropriate adjustment of style-sheet directives), then you may be able to simplify things even further by toggling a single "static" class :
var $next_btn_containers = $('.next_btn_container');
$('#pageborder').waypoint(function(dir) {
$next_btn_containers.toggleClass('static', dir == 'down')
}, { offset: 'bottom-in-view' });
.next_btn_container would thus remain a reliable selector (for other purposes), regardless of the statc/non-static state of the element(s).
Note: Unlike the first version (and your own code), this will not handle two sets of elements toggling in anti-phase, if that's what you have.
I used this code to make it work, thanks to lucuma for pointing me in the right direction!
$('#pageborder').waypoint(function(direction) {
if (direction == 'down') $('.next_btn_container').removeClass('next_btn_container').addClass('next_btn_container_static');
else {
$('.next_btn_container_static').removeClass('next_btn_container_static').addClass('next_btn_container');
}
}, { offset: 'bottom-in-view' });
My name is Adam, I'm new to Stack Exchange, but have found this site very useful for many past problems I have had.
I'm having a problem with a jquery function and thought I'd seek advice here. I have a pretty decent knowledge of html & css, a little of php, but virtually none of javascript or jquery.
I'm currently working on a site that uses specific html tags to enable dynamic content as php isn't permitted. Javascript is however so I've been looking it. I don't have a live example to show you here as I can only preview the design from within my account, however I have pasted the script below.
I wanted to create a responsive design, fluid down to mobile. Following recent design trends, I wanted to create 'Slide in/out' style menus from the side of the screen (think Facebook Mobile, Dolphin Browser). After viewing some examples, I wrote a function which altered the CSS, moving the main div#site template to the right, revealing the left menu. Everything was ok and it worked fine.
Today I decided it would be nice to have 2 slide out menus, one on the left, the other, on the right.
I added to the function what I thought was going to work, and it sort of does.
I have a button (with class .open-sidebar-right) to slide the main site (div#site) to the left, revealing the right hand menu. I can then click either the same button or the div#site to close the menu.
The problem occurs when I click on the left button. The left menu opens and closes absolutely perfectly, however it renders the right button totally useless and doesn't function at all.
I've tried writing it as two separate functions, using one variable for both menus with different values, and it always renders the right button useless after using the left button.
As I mentioned earlier, I have virtually no knowledge of Javascript or jQuery, so it's probably poorly coded, but I can't understand why this wouldn't work.
If anyone has any advice or suggestions I would really appreciate it.
Thanks in advance, Adam.
jQuery(function () {
var sidebarleft;
var sidebarright;
// ------------
// Left sidebar
jQuery(".open-sidebar-left").click(function () {
if (!sidebarleft) {
jQuery("#site").css({
'left':'50%',
});
sidebarleft = true;
return false;
} else {
jQuery("#site").css({
'left':'0%',
});
sidebarleft = false;
return false;
}
});
// ------------
// Right sidebar
jQuery(".open-sidebar-right").click(function () {
if (!sidebarright) {
jQuery("#site").css({
'right':'50%',
});
sidebarright = true;
return false;
} else {
jQuery("#site").css({
'right':'0%',
});
sidebarright = false;
return false;
}
});
// ----------------------------------
// Close sidebars by clicking on site
jQuery("#site").click(function () {
if (sidebarleft) {
jQuery("#site").css({
'left':'0%',
});
sidebarleft = false;
return false;
} else if (sidebarright) {
jQuery("#site").css({
'right':'0%',
});
sidebarright = false;
return false;
}
});
});
Adam,
#zgood says your code is good, but I thought I'd point out a few errors and make some suggestions which may solve your problem:
$(document).ready(function(){ // in the jQuery doc, they don't suggest you use $(<func>)
var sidebarleft = false, // sidebarleft and sidebarright has to be equal to something
sidebarright = false; // either true or false (I would use false since you're testing false in your conditional
$(".open-sidebar-left").click(function() {
if( !sidebarleft ) {
$("#site").css({
left: '50%' // remove the comma, and do not put quotes around single-word identifiers
});
sidebarleft = true;
return false;
} else {
$("#site").css({
left: '0'
});
sidebarleft = false;
return false;
}
});
$(".open-sidebar-right").click(function() {
if( !sidebarright ) {
$("#site").css({
right: '50%' // remove the comma, and do not put quotes around single-word identifiers
});
sidebarright = true;
return false;
} else {
$("#site").css({
right: '0'
});
sidebarright = false;
return false;
}
});
});
So as you can see in the comments in the code above,
jQuery says it's valid, but not suggested that you use jQuery(function(){}); so query the document element then test for ready, then call a function
sidebarright and sidebarleft were undefined (neither true or false) so your
if statements don't make sense.
In the css() declaration, you shouldn't put a comma on the last element. Only put commas if there are more than one element.
I would also suggest using animate() instead of css(), and also (if you're using Chrome) use the inspector and (if you're using Firefox) use FireBug to test for any errors in your javascript code. Hope this helps.
Your code is right, the problem seems to be a CSS issue.
When you click your left button your click event is adding an inline style to your #site div like so:
<div id="site" style="left:50%;">
Then when you click your right button your code appends the new style to your #site div like so:
<div id="site" style="left: 0%; right: 50%;">
See the problem?
To fix this you must do two things. Since you didn't post your CSS, I don't know how you have your #site styled, but remove any left or right style from your #site style declaration.
Next update your jQuery code to remove any previous inline styles like so:
// ------------
// Left sidebar
jQuery(".open-sidebar-left").click(function () {
jQuery("#site").removeAttr('style');
if (!sidebarleft) {
jQuery("#site").css({
'left':'50%',
});
sidebarleft = true;
return false;
} else {
jQuery("#site").css({
'left':'0%',
});
sidebarleft = false;
return false;
}
});
AND
jQuery(".open-sidebar-right").click(function () {
jQuery("#site").removeAttr('style');
if (!sidebarright) {
jQuery("#site").css({
'right':'50%',
});
sidebarright = true;
return false;
} else {
jQuery("#site").css({
'right':'0%',
});
sidebarright = false;
return false;
}
});
removeAttr is your friend here. Also you may want to use an animate instead of just changing the css values, but thats your call
jQuery .animate()
Looked around quite a bit, and can't seem to find a JQuery solution (maybe its just a limitation of JavaScript) for this:
<a href="somelink.php"
onclick="return confirm('Go to somelink.php?');">Click Here</a>
In the above example, when a user clicks on the link, it will only go to its href if the user clicks OK in the confirm box.
What I am trying to do is get a more modern look using a popup div. Perhaps something like this:
<a href="somelink.php"
onclick="return jq_confirm('Go to somelink.php?');">Click Here</a>
(Where jq_confirm is a custom JQuery confirm function that pops up a nice div with a YES/NO or OK/CANCEL button pair).
However, I cannot seem to find any such thing.
I have looked at some JQuery widget libraries etc which offer similar functionality, but none will wait for the response from the user (at least, not in the scenario described above), but instead they just proceed and take the user to the link (or run any JavaScript embedded in the href='' piece of the link). I suspect this is because while you can attach a callback function to many of these widgets to return a true/false value, the onclick event does not wait for a response (callbacks are asynchronous), thereby defeating the purpose of the confirm box.
What I need is the same kind of halt-all-javascript (modal) functionality that the default confirm() command provides. Is this possible in JQuery (or even in JavaScript)?
As I am not an expert in JavaScript nor in JQuery, I defer to you gurus out there. Any JQuery (or even pure JavaScript) solution is welcome (if possible).
Thanks -
I just had to solve the same problem. I wound up using the dialog widget from JQuery UI. I was able to implement this without using callbacks with the caveat that the dialog must be partially initialized in the click event handler for the link you want to use the confirmation functionality with (if you want to use this for more than one link). This is because the target URL for the link must be injected into the event handler for the confirmation button click.
Here's my solution, abstracted away to be suitable for an example. I use a CSS class to indicate which links should have the confirmation behavior.
<div id="dialog" title="Confirmation Required">
Are you sure about this?
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true
});
$(".confirmLink").click(function(e) {
e.preventDefault();
var targetUrl = $(this).attr("href");
$("#dialog").dialog({
buttons : {
"Confirm" : function() {
window.location.href = targetUrl;
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#dialog").dialog("open");
});
}); // end of $(document).ready
</script>
<a class="confirmLink" href="http://someLinkWhichRequiresConfirmation.com">Click here</a>
<a class="confirmLink" href="http://anotherSensitiveLink">Or, you could click here</a>
Check out http://www.84bytes.com/2008/06/02/jquery-modal-dialog-boxes/
They have a good variety of modal-boxes for JQuery.
I think you should see http://www.ericmmartin.com/simplemodal/
A modal dialog override of the JavaScript confirm function. Demonstrates the use of onShow as well as how to display a modal dialog confirmation instead of the default JavaScript confirm dialog.
Did you see the jQuery Modal Dialog on jQuery UI site?
Modal Confirmation Dialog demo
I blogged about the solution to this issue here: http://markmintoff.com/2011/03/asp-net-jquery-confirm-dialog/
Even though the article is geared towards ASP.Net it can be easily adapted to php. It relies on preventing the click with a return false and when the user clicks "OK" or "YES" or what-have-you; the link or button is simply clicked again.
var confirmed = false;
function confirmDialog(obj)
{
if(!confirmed)
{
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Yes": function()
{
$( this ).dialog( "close" );
confirmed = true; obj.click();
},
"No": function()
{
$( this ).dialog( "close" );
}
}
});
}
return confirmed;
}
Give it a try and let me know what you think. I hope this solves your problem.
You should be able to override the standard window.confirm function be writing the following code.
window.confirm = modalConfirm
then you will need to make a function like this
function modalConfirm(message){
// put your code here and bind "return true/false" to the click event
// of the "Yes/No" buttons.
}
This should work, although I haven't tested it yet. I am going to do exactly this right now and will let you all know how it worked.
Edit:
I have tested my example above now and it was not possible, you will have to pass in a callback function to your overwritten confirm function like this:
function modalConfirm(message, callback){
...
$("button.yes").click(function(){
callback(result);
});
...
}
..making your call to the function look like this:
confirm("Are you sure?", function(result){
alert(result);
});
In other words, it is not possible to completely override the default window.confirm function without causing a nasty loop that causes the browser to hang. I think that you will have to modify your confirm calls like above.
Since this question seems to be missing the canonical answer: there is no way to programatically pause (and resume) javascript execution like alert or confirm do.
That being said, relying on this behaviour today is usually considered bad practice given the single threaded nature of javascript, and the reason why the aforementioned functions do pause execution is probably because they were designed when the web was still at a very early stage, and later left unchanged to ensure compatibility. Since the focus nowadays is in writing as much non-blocking js code as possible, it's unlikely the functionality to programmatically halt js will ever make it to any future specification of ECMAScript, so your best bet is to rework your site to make sure confirm and alert dialogs can co-exist with other javascript code running in the background.
My way around this problem was to add some arbitrary data to the object, and check for that data on click. If it existed, proceed with the function as normal, otherwise confirm with a yes/no (in my case using a jqtools overlay). If the user clicks yes - insert the data in the object, simulate another click and wipe the data. If they click no, just close the overlay.
Here is my example:
$('button').click(function(){
if ($(this).data('confirmed')) {
// Do stuff
} else {
confirm($(this));
}
});
And this is what I did to override the confirm function (using a jquery tools overlay):
window.confirm = function(obj){
$('#dialog').html('\
<div>\
<h2>Confirm</h2>\
<p>Are you sure?</p>\
<p>\
<button name="confirm" value="yes" class="facebox-btn close">Yes</button>\
<button name="confirm" value="no" class="facebox-btn close">No</button>\
</p>\
</div>').overlay().load();
$('button[name=confirm]').click(function(){
if ($(this).val() == 'yes') {
$('#dialog').overlay().close();
obj.data('confirmed', true).click().removeData('confirmed');
} else {
$('#dialog').overlay().close();
}
});
}
I have a solution that can be used to replace the default window.confirm function. It doesn't require you overriding window.confirm as that is not fully possible.
My solution allows you to have a general class like me, let's say 'confirm-action' that you place on any element that requires a confirmation before being processed. The script is very simple and utilizes jQuery, jQuery UI Dialog and no other plugins.
You can find the complete demo of the implementation on jsFiddle, http://jsfiddle.net/74NDD/39/.
Usage:
Add this javascript code in your html head or before any other click
binding you have in your javascript.
$("#dialog:ui-dialog").dialog("destroy");
$('.confirm-action').live('click', function(e) {
$self = $(this);
if (e && e.stopImmediatePropagation && $self.data('confirmed') !== true) {
e.stopImmediatePropagation();
$('#confirm-action-dialog').dialog({
height: 110,
modal: true,
resizable: false,
draggable: false,
buttons: {
'Yes': function() {
$(this).dialog('close');
$self.data('confirmed', true);
$self.click();
},
'No': function() {
$self.data('confirmed', false);
$(this).dialog('close');
}
}
});
} else if ($self.data('confirmed') === true) {
e = window.event;
e.cancelBubble = false;
$self.data('confirmed', false);
}
return false;
});
Place this html somewhere in the body (it is hidden by default).
<div style="display:none;" id="confirm-action-dialog" title="Confirm Action?">
<p>
<span class="ui-icon ui-icon-alert"></span>
Are you sure you want to continue?
</p>
</div>
Put the class 'confirm-action' on any element that requires confirmation.
confirm-action
This solution works perfect as it does not alter jQuery event bubbling, it merely pauses (stops) all other events until the user decides what they want to do.
I hope this is helpful for someone else as I was unable to find any other solution that doesn't require me installing another jQuery plugin or do some other hack.
Building on top of Banu's solution (thanks a ton!) to make it a one pop solution on top of each page. Paste this code inside:
$(document).ready
And add "confirmLinkFollow" class to all links you want confirmed:
$(".confirmLinkFollow").click(function(e) {
e.preventDefault();
var targetUrl = $(this).attr("href");
var $dialog_link_follow_confirm = $('<div></div>').
html("<p>Are you sure?</p>").
dialog({autoOpen: false,
title: 'Please Confirm',
buttons : {
"Confirm" : function() {
window.location.href = targetUrl;
},
"Cancel" : function() {
$(this).dialog("close");
}
},
modal: true,
minWidth: 250,
minHeight: 120
}
);
$dialog_link_follow_confirm.dialog("open");
});
Put the redirect inside the function like:
<script>
function confirmRedirect(url, desciption) {
if (confirmWindow(desciption)) {
window.location = url;
}
}
</script>
And call it like this:
Go!
Almost three years later, I am looking for something similar. Since I have not found an acceptable "quick" solution, I wrote something that comes very close to the criteria of the OP. I figure others may find it useful in the future.
JavaScript is event-driven and that means it does not support any sort of "wait" or "sleep" loop that we can use to pause a pure-javascript confirm function. The options involve burning processor cycles, using a browser plugin, or AJAX. In our increasingly mobile world, and with sometimes spotty internet connections, none of these are great solutions. This means that we have to return from our "confirm" function immediately.
However, since there is no "false" logic in the code snippet above (ie. nothing is done when the user clicks "Cancel"), we can trigger the "click" or "submit" event again when the user clicks "OK." Why not set a flag and react based on that flag within our "confirm" function?
For my solution, I opted to use FastConfirm rather than a "modal" dialog. You can easily modify the code to use anything you want but my example was designed to use this:
https://github.com/pjparra/Fast-Confirm
Due to the nature of what this does, I do not see a clean way to package it up. If you feel that this has too many rough edges, feel free to smooth them out or rewrite your code the way that everyone else has recommended:
/* This version of $.fn.hasEvent is slightly modified to provide support for
* the "onclick" or "onsubmit" tag attributes. I chose this because it was
* short, even if it is cryptic.
*
* Learn more about the code by Sven Eisenschmidt, which is licensed under
* the MIT and GPL at:
* http://github.com/fate/jquery-has-event
*/
(function($) {
$.fn.hasEvent = function(A, F, E) {
var L = 0;
var T = typeof A;
E = E ? E : this;
var V = (E.attr('on'+A) != undefined);
A = (T == 'string') ? $.trim(A) : A;
if (T == 'function')
F = A, A = null;
if (F == E)
delete(F);
var S = E.data('events');
for (e in S)
if (S.hasOwnProperty(e))
L++;
if (L < 1)
return V; // = false;
if (A && !F) {
return V = S.hasOwnProperty(A);
} else if(A && S.hasOwnProperty(A) && F) {
$.each(S[A], function(i, r) {
if(V == false && r.handler == F) V = true;
});
return V;
} else if(!A && F) {
$.each(S, function(i, s) {
if (V == false) {
$.each(s, function(k, r) {
if (V == false && r.handler == F)
V = true;
});
}
});
}
return V;
}
$.extend($, {hasEvent: $.fn.hasEvent});
}) (jQuery);
/* Nearly a drop-in replacement for JavaScript's confirm() dialog.
* Syntax:
* onclick="return jq_confirm(this, 'Are you sure that you want this?', 'right');"
*
* NOTE: Do not implement "false" logic when using this function. Find another way.
*/
var jq_confirm_bypass = false;
function jq_confirm(el, question, pos) {
var override = false;
var elem = $(el);
if ($.fn.fastConfirm == undefined) {
override = confirm(question);
} else if (!jq_confirm_bypass) {
if (pos == undefined) {
pos = 'right';
}
elem.fastConfirm({
position: pos,
questionText: question,
onProceed: function(trigger) {
var elem = $(trigger);
elem.fastConfirm('close');
if (elem.hasEvent('click')) {
jq_confirm_bypass = true;
elem.click();
jq_confirm_bypass = false;
}
if (elem.hasEvent('submit')) {
jq_confirm_bypass = true;
elem.submit();
jq_confirm_bypass = false;
}
// TODO: ???
},
onCancel: function(trigger) {
$(trigger).fastConfirm('close');
}
});
}
return override ? override : jq_confirm_bypass;
}
So... onclick="return confirm('Do you want to test this?');" would become onclick="return jq_confirm(this, 'Do you want to test this?');" The pos/"right" parameter is optional and is specifically for Fast-Confirm.
When you click, the jq_confirm() function will spawn the jQuery dialog and return "false." When the user clicks "OK" then jq_confirm() sets a flag, calls the original click (or submit) event, returns "true", then unsets the flag in case you want to remain on the same page.
The following link has a jQuery plugin for confirm boxes similar to constructing like confirm("something") in JavaScript
http://labs.abeautifulsite.net/archived/jquery-alerts/demo/