Combining multiple JQuery UI statements to set up Button controls - jquery-ui

I'm pretty new to JQuery and JQuery-UI, but I'm having fun with it so far. My Javascript skills are a bit rusty, however, so some things are giving me a bit of a headache.
I'm using Jquery UI to theme my site, and I have several buttons that I want to set up with the appropriate theme. Each button has a different icon, so I ended up with a bunch of statements that look like this:
<script type="text/javascript">
$(function() {
$('[id$="butFind"]').button({
icons: {
primary: 'ui-icon-search'
}
});
});
$(function() {
$('[id$="butUpdate"]').button({
icons: {
primary: 'ui-icon-disk'
}
});
});
$(function() {
$('[id$="butCancel"]').button({
icons: {
primary: 'ui-icon-cancel'
}
});
});
// and so on for several more controls
</script>
I'm using the [id$=] ("ID ends with") selector as the controls that I'm theming are ASP.NET LinkButtons on a Content Page based off of a Master Page, and they get renamed when rendered to something like "ctl00_ContentPlaceHolder1_butFindSku". The ASP.NET markup for the buttons is pretty simple, and looks like:
<asp:LinkButton ID="butUpdate" runat="server" Text="Update"
CommandName="Update" />
<asp:LinkButton ID="butCancel" runat="server" Text="Cancel"
CommandName="Cancel" />
The multiple functions to theme the buttons and designate the appropriate icons seems rather awkward to me. I keep thinking that I should be able to either loop through some defined array of controls and icons, or tackle it in some other way that would make it easier for me in the future, particularly when I'm adding other controls to the page.
Suggestions on better ways to set this up are appreciated! Thanks!

I would have suggested to associate the icons with the buttons using HTML5 data- attributes, but since you're using ASP.NET web controls it will be more complicated than it's worth.
You can, however, store the id suffixes and their respective icons in an object literal, and use $.each() to iterate over it:
$.each({
butFind: "search",
butUpdate: "disk",
butCancel: "cancel"
}, function(suffix, icon) {
$("[id$='" + suffix + "']").button({
icons: {
primary: "ui-icon-" + icon
}
});
});

Related

Jquery mobile How to tap the screen to no avail

I tested on the Apple device, and when I click on the screen when there is no effect. This is my code. Click on the events of this writing there are questions?
<script>
$(function() {
$('#test').tap(function() {
$('#menuNum').text('1');
})
})
</script>
You need to change few things.
Do not use $(function() { or classic document ready to check for a correct state, they can cause problems with jQuery Mobile. Instead use jQuery Mobile alternative called page events.
Then don't bind tap event like that, use proper modern way of doing that. In your case element must be loaded into the DOM for that kind of binding to work. And because of $(function() { sometimes it can happen that element is still loading when binding is executed. So use it like this:
$(document).on('tap','#test',function() {
$('#menuNum').text('1');
});
This method don't care if element exist or not, it will even work if element is loaded into the DOM after binding process.
Working example: http://jsfiddle.net/Gajotres/SQ7DF/
In the end you want something like this:
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('tap','#test',function() {
alert('Tap');
});
});

Controling height in jQuery UI Accordion with dynamic data

I'm using an jQuery accordion control with knockout to dynamically add/remove items to the control based on some client-side activity. I've created a knockout binding like such:
ko.bindingHandlers.accordion = {
init: function (element, valueAccessor) {
var options = valueAccessor() || {};
setTimeout(function () {
$(element).accordion(options);
}, 0);
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).accordion("destroy");
});
},
update: function (element, valueAccessor) {
var options = valueAccessor() || {};
$(element).accordion("destroy").accordion(options);
}
}
Now my problem is the sizing of the accordion... it always looks very compressed (vertically). I've tried setting the height of the DIV that contains the control, like this:
<div id="LearningPaths" data-bind="foreach: allLearningPaths, accordion: {}" style="height:500px; border:1px solid red;">
But the panels in the accordion don't change... they still aren't very "tall". Here's what it looks like: http://sdrv.ms/STA9Y6
I think there's a setting I can pass in when I use the .accordion(), but with my binding handler I'm not sure how to do that as I'm already passing in the 'options' object.
What I want is to have the content area of each panel to expand to the entire available side in the accordion control... ideas?
First i think your problem is someone related to SharePoint web parts. I created a accordion solution which is based on the summary link web part in SharePoint and can be found here: http://www.n8d.at/blog/turn-summary-link-web-part-into-an-accordion/
I wrote my own accordion to accomplish this, which also makes sure that if you like to edit the page the accordion script won't be loaded.
On the other hand i think your problem is more related to css and not to jquery. Do you use float style in your css? Then you need to make sure that you use the so called clear-fix.
This can be done in define the following style:
.panel:after{
clear: both;
}

What is the best practice for opening a jquery dialog from angular?

Heres the html:
<div ng-controller="MyCtrl">
<a ng-click="open()">Open Dialog</a>
<div id="modal-to-open" title="My Title" ui-jq="dialog" ui-options="{width: 350, autoOpen: false, modal: true}">
Dialog Text
</div>
</div>
And here's the js:
function MyCtrl($scope)
{
$scope.open = function () {
$('#modal-to-open').dialog('open');
}
}
Is this the best way to go about doing this? It seems like there could be a better way of opening it without accessing the DOM but I am not sure how I would go about that. The above code works, I am just wondering if this is the way I should go about doing this. Any input is welcome.
"Best practice" is fuzzy ground here. If it's readable and it works, then you're 90% there, IMO, and it's probably fine.
That said, the "angular way" is to keep DOM manipulation out of the controller, and to use dependency injection to make sure everything is testable. Obviously the way you illustrated above would be hard to test, and puts some DOM manipulation in the controller.
I guess what I would do to get the DOM manipulation out of the controller is use a directive:
A simple directive to tie your dialog open call to a click on an element:
app.directive('openDialog', function(){
return {
restrict: 'A',
link: function(scope, elem, attr, ctrl) {
var dialogId = '#' + attr.openDialog;
elem.bind('click', function(e) {
$(dialogId).dialog('open');
});
}
};
});
And in mark up it would be used like so:
<button open-dialog="modal-to-open">Open Dialog</button>
Now, this is obviously very basic. You could get pretty advanced with this if you wanted to, adding additional attributes for different options in the dialog.
You could go even further and add a Service that opened the dialog for you, so you could inject it into your controller or even your directive, and get the call out of there that way. For example:
app.factory('dialogService', [function() {
return {
open: function(elementId) {
$(elementId).dialog('open');
}
};
}]);
And here it is in use. It seems silly because it's essentially the same thing. But that's mostly because it's a very simplistic example. But it at least leverages DI and is testable.
app.controller('MyCtrl', function($scope, dialogService) {
$scope.open = function () {
dialogService.open('#modal-to-open');
};
});
Anyhow. I hope all of that helps you decide what path you want to take. There are a thousand ways to do this. The "right" way is whatever works, allows you to do whatever you need to do (testing or anything else), and is easy to maintain.

How do you remove a button's active state with jQuery Mobile?

In my mobile app, using jQuery Mobile...
I would like to make a simple button execute a simple javascript function on click. No page transitions, nothing special like that.
I understood I can eliminate the page transitions by doing return false or preventDefault()
But the problem is the button sticks with the "active" state, i.e. highlighted blue if you use the general theme. I'm wondering how I can remove that after click (or tap, etc).
Thanks.
You can disable the 'highlighted blue'-state in the 'mobileinit'-event before loading jQueryMobile-script:
<head>
<script>
$(document).bind('mobileinit', function () {
$.mobile.activeBtnClass = 'unused';
});
</script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
</head>
Now, when you click on a link, no class will be added after the click is performed. You will still have the 'hoover' and 'down' classes.
Update:
This question and the hacks suggested are now a bit outdated. jQuery mobile handles buttons quite a bit differently than 3 years ago and also, jQuery mobile now has several different definitions of "button". If you want to do what the OP was looking for, you might now be able to avoid the issue by using this:
Step 1:
<button class="ui-btn myButton">Button</button>
Alternatively, you could also use jQuery mobile input buttons:
<form>
<input value="Button One" type="button" class="myButton">
<input value="Button Two" type="button" class="myButton2">
</form>
Step 2:
Then your standard jquery on callback:
$(".myButton").on("tap", function(e) {
// do your thing
});
If you are using a button or a tab, or whatever, that has the "active" class applied to it (the default is ui-btn-active), the old answer may still be useful to someone. Also, here is a fiddle demonstrating the code below.
Selectively removing active state:
As demonstrated in another answer, you can disable the active state for all buttons on all pages. If that is acceptable for the project in question, that is the appropriate (and simpler) solution. However, if you want to disable the active state for some buttons while preserving active states for others, you can use this method.
Step 1:
$(document).bind('mobileinit', function() {
$(document).on('tap', function(e) {
$('.activeOnce').removeClass($.mobile.activeBtnClass);
});
});
Step 2:
Then add the activeOnce class (or whatever you want to call it - it's a custom class) to the buttons that you don't want to highlight when clicking.
And as is usual when binding anything to mobileinit, be sure you place your bindings - and perhaps better, all your javascript code - below the jQuery script and above the jQuery-mobile script.
<script src="js/jquery.js"></script>
<script src="js/my_script.js"></script>
<script src="js/jquery.mobile.js"></script>
Do NOT set the activeBtnClass to '' as suggested, this will cause errors when closing dialogs and the pageLoading function.
The method described does work, but cannot be set to null, the activeBtnClass variable is used as a selector, so set it to a non-existent class to get the same effect without the error.
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).bind('mobileinit', function () {
$.mobile.activeBtnClass = 'aBtnSelector';
});
</script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
</head>
This works well to remove the highlight from the buttons while keeping the active state on other elements.
you can just do it via css instead of java:
eg: (you get the idea)
#cart #item_options .ui-btn-active, #cart #item_options .ui-btn-hover-d, #cart #item_options .ui-btn-up-d, #cart #item_options .ui-link-inherit{
background:inherit;
color:inherit;
text-shadow:inherit;
}
What I do is force the buttons to revert to inactive state before a page changes.
//force menu buttons to revert to inactive state
$( '.menu-btn' ).on('touchend', function() {
$(this).removeClass("ui-btn-active");
});
If you want to support non touch devices you should add timeout.
$('.btn' ).on('touchend click', function() {
var self = this;
setTimeout(function() {
$(self).removeClass("ui-btn-active");
},
0);
});
I have spent the good part of a day and night finding the answer to this problem mainly occurring on an android running phonegap. Instead of the standard JQM buttons I am using custom images with :active state in CSS. After following the link to the next page, then clicking back, the button would just stay in the :active state. I have tried adding classes and removing classes and various other suggestions and nothing has worked.
So I came up with my own little fix which works a treat and may help anyone else that is sitting here stumped. I simply call this snippet of code on 'pagecontainerchange' using data.toPage[0].id to only call it on the page where the active state stuck is occurring. Just make sure to wrap your buttons in a div, in my case called "themenu".
function ResetMenu() {
var menuHtml = $("#themenu").html();
$("#themenu").empty().html(menuHtml).trigger("create");
}
This works for a button in the JqueryMobile headerTab
<style>
.Foo {
color: #FFF !important;
background: #347b68 !important;
}
</style>
<div id="headerTab" data-id="headerTab" data-role="navbar">
<ul id="header_tabs">
<li>name
</li>
</ul>
</div>

Setting dialog overlay Jquery

I want to set the overlay of a jQuery dialog to an image, and can't seem to manage the task.
I have other dialogs on the pages that I want to no have the background images, so setting the css for the overlay background won't work as a blanket solution.
I have tried a lot of different methods, and I believe there is a timing issue with the appliction of the jQuery command to set the overlay with css and the actual dialog div's and css getting added to the DOM.
Here is what I have tried so far.
$('#submitUpload').click(function(){
$("#uploadStart").dialog('open');
$(".ui-widget-overlay").css({'background-image': 'url("http://www.mydomain.com/images/ftp-page-bg.gif")','opacity':'1'})
$("#uploadForm").submit();
});
OR
$("#uploadStart").dialog({
autoOpen: false,
width: 400,
modal: true,
closeOnEscape: false,
draggable: false,
resizable: false,
open: function(event, ui) {
$(".ui-dialog-titlebar-close").hide();
$(".ui-widget-overlay").css({'background-image': 'url("http://www.mydomain.com/images/ftp-page-bg.gif")','opacity':'1'})
}
});
I have also tried using the dialogClass method on the dialog code with no success.
With both the absolute url and the relative, and the url in quotes or with no quotes.
The image exists in the directory.
Anyone have any ideas on how to get jQuery to apply with the correct timing to display the image as the overlay?
Thanks!
Update
The dialog class designation will allow you to set classes for the overal dialog. I was actually looking to just tap into the specific ui-widget-overlay class and over-ride the background image there. I found that trying to override the background using the dialogClass worked for overriding the background of the dialog, not the overlay background.
When the dialog is added to the DOM, jQuery loads it's div's right before the body tag.
I found a solution, being that in the open method for the dialog, I used
$(".ui-widget-overlay").addClass('artFTP');
to add a class
.artFTP{background-image: url(../../images/ftp-page-bg.gif); opacity:1;}
and made sure it was the last class in the file that would overwrite the overlay background image.
I hope this helps someone.
Thanks and +1 to jjross, your answer got me to jump back into the jQuery docs.
If anyone has a better solution, please post. I would be happy to see it. I think there might be a way to use CSS to accomplish the task, but (for the life of me) couldn't figure it out.
You should be able to add the class to the div in your HTML code prior to jquery being called on it. In my testing, this automatically added that class to the dialog when it was created.
In the new class, you should be able to specify a background image.
For example:
calling:
$("#dialog").dialog();
on
<div id="dialog" class="thisClass" title="Edit Case Status">
<div>some stuff</div>
</div>
causes the dialog to be created with the
"thisClass" class.
as an alternative option, it looks like the dialog has a "dialogClass" method. It will let you add your own class to the dialog (in that class, you can define the background). From the docs:
The specified class name(s) will be added to the dialog, for additional theming.
Code examples
Initialize a dialog with the dialogClass option specified.
$( ".selector" ).dialog({ dialogClass: 'alert' });
Get or set the dialogClass option, after init.
//getter
var dialogClass = $( ".selector" ).dialog( "option", "dialogClass" );
//setter
$( ".selector" ).dialog( "option", "dialogClass", 'alert' );
I encountered the same problem and found In this case your question. I didn't find any solution that could satisfy me, so I did something on my own.
First, let me introduce my problem.
I have a page, where I have two kinds of dialogs. Dialogs with video and dialogs with message (like alert, confirmation, error etc.). As we know, we can set a different class for a dialog, but we can't set class for different overlay. So question was, how to set a different behavior for different overlays?
So I dig, I dig deeper than Dwarves in Moria into jQuery ui code itself. I found out, that actualy there is an unique overlay for each dialog. And it is created in "private" function _createOverlay which is not accessible. In fact, I found function via jquery ui namespace as $.ui.dialog.prototype._createOverlay. So I was able to make a small extension with logic based on class:
(function() {
// memorize old function
var originFn = $.ui.dialog.prototype._createOverlay;
// make new function
$.ui.dialog.prototype._createOverlay = function() {
originFn.call(this); // call old one
// write your own extension code there
if (this.options["dialogClass"] === "video-dialog") {
var overlay = this.overlay; // memorize overlay (it is in old function call as this.overlay)
var that = this; // just cause bind is event
// my own extenstion, when you click anywhere on overlay, dialog is closed + I change css
overlay.bind('click', function() {
that.close(); // it is same like element.dialog('close');
}).css({
"background": "none",
"background-image": "url(\'files/main-page/profile1.png\')" // this didnt work for you, but works for me... maybe I have newer version of jQuery.UI
// anyway, once you have overlay as variable, Im sure you will be able to change its css
});
}
};
})();
I hope this will help others :)

Resources