How do I add a custom icon to a standard jQuery UI theme? - jquery-ui

It is easy to use one of the icons available from the standard icon set:
$("#myButton").button({icons: {primary: "ui-icon-locked"}});
But what if I want to add one of my own icons that is not part of the framework icon set?
I thought it would be as easy as giving it your own CSS class with a background image, but that doesn't work:
.fw-button-edit {
background-image: url(edit.png);
}
Any suggestions?

I could also recommend:
.ui-button .ui-icon.your-own-custom-class {
background-image: url(your-path-to-normal-image-file.png);
width: your-icon-width;
height: your-icon-height;
}
.ui-button.ui-state-hover .ui-icon.your-own-custom-class {
background-image: url(your-path-to-highlighted-image-file.png);
width: your-icon-width;
height: your-icon-height;
}
then just type in the JS code:
jQuery('selector-to-your-button').button({
text: false,
icons: {
primary: "you-own-cusom-class" // Custom icon
}});
It worked for me and hope it works for you too!

I believe the reason why his won't work is because you're icon's background-image property is being overridden by the jQuery UI default sprite icon background image. The style in question is:
.ui-state-default .ui-icon {
background-image: url("images/ui-icons_888888_256x240.png");
}
This has higher specificity than your .fw-button-edit selector, thus overriding the background-image proerty. Since they use sprites, the .ui-icon-locked ruleset only contains the background-position needed to get the sprite image's position. I believe using this would work:
.ui-button .ui-icon.fw-button-edit {
background-image: url(edit.png);
}
Or something else with enough specificity. Find out more about CSS specificity here: http://reference.sitepoint.com/css/specificity

This is based on the info provided by Yi Jiang and Panayiotis above, and the jquery ui button sample code:
As I was migrating an earlier JSP application that had a toolbar with images per button, I wanted to have the image inside the button declaration itself rather than create a separate class for each toolbar button.
<div id="toolbarDocs" class="tableCaptionBox">
<strong>Checked Item Actions: </strong>
<button id="btnOpenDocs" data-img="<s:url value="/images/multi.png"/>">Open Documents</button>
<button id="btnEmailDocs" data-img="<s:url value="/images/email.png"/>">Attach to Email</button>
</div>
Of course there were plenty more buttons than just the two above. The s tag above is a struts2 tag, but you could just replace it with any URL
<button id="btnOpenDocs" data-img="/images/multi.png">Open Documents</button>
The below script looks for the attribute data-img from the button tag, and then sets that as the background image for the button.
It temporarily sets ui-icon-bullet (any arbitrary existing style) which then gets changed later.
This class defines the temporary style (better to add further selectors for the specific toolbar if you plan to use this, so that the rest of your page remains unaffected). The actual image will be replaced by the Javascript below:
button.ui-button .ui-icon {
background-image: url(blank.png);
width: 0;
height: 0;
}
and the following Javascript:
$(document).ready(function () {
$("#toolbarDocs button").each(
function() {
$(this).button(
{ text: $(this).attr('data-img').length === 0? true: false, // display label for no image
icons: { primary: "ui-icon-bullet" }
}).css('background-image', "url(" + $(this).attr('data-img') +")")
.css('background-repeat', 'no-repeat');
});
});

The solution at this link worked great for me:
http://www.jquerybyexample.net/2012/09/how-to-assign-custom-image-to-jquery-ui-button.html
$(document).ready(function() {
$("#btnClose")
.text("")
.append("<img height="100" src="logo.png" width="100" />")
.button();
});​

My solution to add custom icons to JQuery UI (using sprites):
CSS:
.icon-example {
background-position: 0 0;
}
.ui-state-default .ui-icon.custom {
background-image: url(icons.png);
}
.icon-example defines position of icon in custom icons file. .ui-icon.custom defines the file with custom icons.
Note: You may need to define other JQuery UI classes (like .ui-state-hover) as well.
JavaScript:
$("selector").button({
icons: { primary: "custom icon-example" }
});

Building on msanjay answer I extended this to work for custom icons for both jquery ui buttons and radio buttons as well:
<div id="toolbar">
<button id="btn1" data-img="/images/bla1.png">X</button>
<span id="radioBtns">
<input type="radio" id="radio1" name="radName" data-mode="scroll" data-img="Images/bla2.png"><label for="radio1">S</label>
<input type="radio" id="radio2" name="radName" data-mode="pan" data-img="Images/bla3.png"><label for="radio2">P</label>
</span>
</div>
$('#btn1').button();
$('#radioBtns').buttonset();
loadIconsOnButtons('toolbar');
function loadIconsOnButtons(divName) {
$("#" + divName + " input,#" + divName + " button").each(function() {
var iconUrl = $(this).attr('data-img');
if (iconUrl) {
$(this).button({
text: false,
icons: {
primary: "ui-icon-blank"
}
});
var imageElem, htmlType = $(this).prop('tagName');
if (htmlType==='BUTTON') imageElem=$(this);
if (htmlType==='INPUT') imageElem=$("#" + divName + " [for='" + $(this).attr('id') + "']");
if (imageElem) imageElem.css('background-image', "url(" + iconUrl + ")").css('background-repeat', 'no-repeat');
}
});
}

// HTML
<div id="radioSet" style="margin-top:4px; margin-left:130px;" class="radio">
<input type="radio" id="apple" name="radioSet" value="1"><label for="apple">Apple</label>
<input type="radio" id="mango" name="radioSet" value="2"><label for="mango">Mango</label>
</div>
// JQUERY
// Function to remove the old default Jquery UI Span and add our custom image tag
function AddIconToJQueryUIButton(controlForId)
{
$("label[for='"+ controlForId + "'] > span:first").remove();
$("label[for='"+ controlForId + "']")
.prepend("<img position='fixed' class='ui-button-icon-primary ui-icon' src='/assets/images/" + controlForId + ".png' style=' height: 16px; width: 16px;' />");
}
// We have to call the custom setting to happen after document loads so that Jquery UI controls will be there in place
// Set icons on buttons. pass ids of radio buttons
$(document).ready(function () {
AddIconToJQueryUIButton('apple');
AddIconToJQueryUIButton('mango');
});
// call Jquery UI api to set the default icon and later you can change it
$( "#apple" ).button({ icons: { primary: "ui-icon-gear", secondary: null } });
$( "#mango" ).button({ icons: { primary: "ui-icon-gear", secondary: null } });

in css
.ui-button .ui-icon.custom-class {
background-image: url(your-path-to-normal-image-file.png);
width: your-icon-width;
height: your-icon-height;
}
.ui-state-active .ui-icon.custom-class, .ui-button:active .ui-icon.custom-class {
background-image: url(your-path-to-highlighted-image-file.png);
width: your-icon-width;
height: your-icon-height;
}
in HTML
<button type="button" class="ui-button ui-widget ui-corner-all">
<span class="custom-class"></span> CAPTION TEXT
</button>
in JavaScript
$("selector").button({
icons: { primary: "custom-class" }
});

Related

removeEventListener from another array-prototype forEach

Hello, friends!
I'm new to Javascript. Using native JS.
I need when I click on the red button the blue button becomes disabled using removeEventListener. And vice versa - clicking on the blue button will add removeEventListener to the red button.
But my method does not work because the first array does not see the other array.
Thanks for the help. And, please, add comments to your code))
Here is the code and example https://jsfiddle.net/of83ycmx/
<body>
<button class="red">Red</button>
<button class="blue">Blue</button>
<div class="box">BOX</div>
<button class="red">Red</button>
<button class="blue">Blue</button>
<div class="box">BOX</div>
<script>
const box = document.querySelectorAll('.box');
const red = document.querySelectorAll('.red');
const blue = document.querySelectorAll('.blue');
red.forEach((item, i) => {
item.addEventListener('click', function redListener() {
box[i].classList.add('redBox');
//removeEventListener doesnt work because blueListener is not defined
//item.removeEventListener('click', blueListener);
});
});
blue.forEach((item, i) => {
item.addEventListener('click', function blueListener() {
box[i].classList.add('blueBox');
// item.removeEventListener('click', redListener)
});
});
</script>
made some changes that made sense to me. I am quite a beginner, so anyone who sees anything no-no or bad practice go ahead and call me out.
What should happen:
My interpretation of your explanation is this: When a user clicks on 1 of 2 buttons, the button that was NOT clicked should have its event listener removed.
Solution:
Making the functions accessible was your main problem-named functions inside of event listeners are limited to that listener (I assume). So instead move the function outside of the listener and simply call the function:
function blueListener () {
// Do stuff here
}
item.addEventListener('click', blueListener)
Now the function is accessible to the other function, so when you remove the event listener you wont get blueListener is not defined.
By wrapping the buttons and the box in a div allows you to select the button you need. Using .querySelectorAll() on the parent div allows you to select the button with the respective class (i. e the selecting the blue button when you click the red button).
The functions don't need any other info; they use this to access the clicked element. Then you can find the parent element, and select the box to change the background color, and select the respective button to remove the event listener.
DEMO:
const box = document.querySelectorAll('.box');
const red = document.querySelectorAll('.red');
const blue = document.querySelectorAll('.blue');
function redListener() {
var parent = this.parentElement;
var box = parent.querySelectorAll('.box')[0]
var blueButton = parent.querySelectorAll('.blue')[0]
box.classList.add('redBox');
blueButton.removeEventListener('click', blueListener)
}
function blueListener() {
var parent = this.parentElement;
var box = parent.querySelectorAll('.box')[0]
var redButton = parent.querySelectorAll('.red')[0]
box.classList.add('blueBox');
redButton.removeEventListener('click', redListener)
}
red.forEach((item, i) => {
item.addEventListener('click', redListener)
})
blue.forEach((item, i) => {
item.addEventListener('click', blueListener)
});
body {
font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;
}
.box {
width: 100px;
height: 100px;
background-color: rgb(172, 172, 172);
margin: 0px 0px 40px 0px;
display: flex;
justify-content: center;
align-items: center;
}
.redBox {
background-color: rgb(156, 56, 56);
}
.blueBox {
background-color: rgb(66, 56, 156);
}
<div class="buttons">
<button class="red">Red</button>
<button class="blue">Blue</button>
<div class="box">BOX</div>
</div>
<div class="buttons">
<button class="red">Red</button>
<button class="blue">Blue</button>
<div class="box">BOX</div>
</div>

Modal box "hidden" behind greyed out area

Im following along with http://multiplethreads.wordpress.com/tag/pagedown/
The example in the link above makes use of twitter bootstrap whereas i make use of zurb foundation.
Basically im trying to get a custom dialog box to insert images from my pagedown editior (sort of like how stackoverflow does it).
Im abale to pull up the modal box (foundation reveal) but it seems to be "behind" something and i cant seem to interact with it. Any ideas?
My code:
js file:
PH.ui.markdown = {
initialize: function () {
var markdownTextArea = $('textarea[data-markdown=true]');
if (markdownTextArea.length == 1) {
markdownTextArea.addClass('wmd-input')
.wrap("<div class='wmd-panel' />")
.before("<div id='wmd-button-bar'></div>")
.after("<div id='wmd-preview' class='wmd-preview'></div>");
var converter = Markdown.getSanitizingConverter();
var editor = new Markdown.Editor(converter);
editor.hooks.set("insertImageDialog", function (callback) {
//setTimeout(function () {
$('#myModal').foundation('reveal', 'open');
// }, 5000);
return true; // tell the editor that we'll take care of getting the image url
});
editor.run();
}
}
};
html:
<div id="myModal" class="reveal-modal">
<h2>Upload Image</h2>
<%= f.file_field :image %>
<button class="btn" id="insert_image_post">Insert Image</button>
<!-- <a class="close-reveal-modal">×</a> -->
</div>
I figured it out.
The wmd-prompt-background had a z-index of 1000:
<div class="wmd-prompt-background" style="position: absolute; top: 0px; z-index: 1000; opacity: 0.5; height: 1085px; left: 0px; width: 100%;"></div>
So i just added:
<style type="text/css">
#myModal {
z-index: 1500;
}
</style>
to my page and it worked.
One way to do it is to position the div of your modal directly under the <body>. This way you make sure that the modal is not part of elements with special z-index

How can I make a jQuery Mobile dialog that is not full screen?

I'd like to pop up a dialog that is not full screen, i.e., it "floats" above the page which opened it. Here is what I am trying:
<div data-role="page" id='Page1'>
<div data-role='button' id="Button1">Open Dialog</div>
</div>
<div data-role="dialog" id='Dialog'
style='width:200px; height:100px; top:100px; left:100px;'>
<div data-role='button' id="Button2">Close</div>
</div>
<script>
Button1.onclick = function() {
//$.mobile.changePage($('#Dialog'))
$.mobile.changePage('#Dialog',{role:'dialog'})
}
Button2.onclick = function() {
$(".ui-dialog").dialog("close");
}
Even though I set the bounds on Dialog's div, it is still full screen.
Here's what I came up with (after some great hints from Jasper):
<div data-role="page" id='Page1'>
<div data-role='button' id="Button1" >Open Dialog</div>
</div>
<div data-role="dialog" id='Dialog'>
<div data-role='header'id='Dialog_header'><h1>Dialog</h1></div>
<div data-role='button' id="Button2">Close</div>
</div>
<script>
Dialog_header.onclick= function(e){
$("#Dialog").fadeOut(500);
}
Button1.onclick = function(e) {
var $dialog=$("#Dialog");
if (!$dialog.hasClass('ui-dialog'))
{$dialog.page()};
$dialog.fadeIn(500);
}
Button2.onclick = function() {
$("#Dialog").fadeOut(500);
}
Button2 is a bonus: it shows how to close the dialog from code.
You can fiddle with it here:
http://jsfiddle.net/ghenne/Y5XVm/1/
You can force a width on the dialog like this:
.ui-mobile .ui-dialog {
background : none !important;
width : 75% !important;
}​
Notice I also removed the background so the dialog can appear on top of the other page. The only problem that remains is that when you navigate to the dialog, the other page is hidden so the dialog appears on top of a white background.
Here is a demo: http://jsfiddle.net/jasper/TTMLN/
This is a starting point for you, I think the best way to create your own popup is to manually show/hide the dialog so jQuery Mobile doesn't hide the old page.
Update
You can certainly use a dialog as a popup with a small amount of custom coding:
$(document).delegate('#dialog-link', 'click', function () {
var $dialog = $('#dialog');
if (!$dialog.hasClass('ui-dialog')) {
$dialog.page();
}
$dialog.fadeIn(500);
return false;
});​
Where dialog-link is the ID of the link that opens the dialog as a popup.
Here is a slight update to the CSS to center the modal horizontally:
.ui-mobile .ui-dialog {
background : none !important;
width : 75% !important;
left : 50% !important;
margin-left : -37.5% !important;
}​
And here is a demo: http://jsfiddle.net/jasper/TTMLN/1/
here is a plugin that u can use..this plugin is also customizable with ur own html.
simpleDialogue plugin for jquery mobile

Refresh jquery ui dialog position

I'm using a jquery dialog.
The content of this dialog is dynamic so the height change when the dialog is open.
$("#a_div").dialog({ width: 400 });
The dialog initially appears center in the page. but when the height change is no more center.
How can i refresh the dialog's position without close and reopen it?
thanks
You need to re-set the position by doing:
$("#a_div").dialog({
position: { 'my': 'center', 'at': 'center' }
});
The position is set once when creating the dialog, but can be altered afterwards (or just re-set at the same value, forcing jQuery to recalculate).
See this demo: http://jsfiddle.net/petermorlion/3wNUq/2/
If you want to use the exact position settings as used by jquery ui for the initial positioning, you can grab the options from the jquery ui code and use them again any time you want to reposition your dialog.
function refreshDialogPosition(id) {
$("#" + id).position({
my: "center",
at: "center",
of: window,
collision: "fit",
// Ensure the titlebar is always visible
using: function (pos) {
var topOffset = $(this).css(pos).offset().top;
if (topOffset < 0) {
$(this).css("top", pos.top - topOffset);
}
}
});
}
Use:
refreshDialogPosition("YourDialogId");
This will also make sure your title bar is always visible. Otherwise your title bar will be outside your screen when using dialogs with large content. (content height > window height)
Have a nice day.
You can try to resize the dialog using its classes by JQuery directly (documentation here)
The basic structure of JQueryUI Dialog is this:
<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable">
<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
<span id="ui-dialog-title-dialog" class="ui-dialog-title">Dialog title</span>
<a class="ui-dialog-titlebar-close ui-corner-all" href="#"><span class="ui-icon ui-icon-closethick">close</span></a>
</div>
<div style="height: 200px; min-height: 109px; width: auto;" class="ui-dialog-content ui-widget-content" id="dialog">
<p>Dialog content goes here.</p>
</div>
</div>
So, maybe you should play with classes's width and height to set the best.
Another solution is to set dialog's width directly before open (when your data is successfully loaded):
$("#a_div").dialog({ width: 400 });
$.get('my_url.php',function(data){
$('#a_div .ui-dialog').css('width','400px');
// Or...
$('#a_div').css('width','400px');
});
I hope it helps you.
Marked as Correct didn't work for me. It persists position once it opened.
Following code will reset dialog position, every time you open/re-open it.
$dlg.dialog({
open: function(event, ui) {
// Reset Dialog Position
$(this).dialog('widget').position({ my: 'center', at: 'center', of: window });
}
});
$dlg.dialog('open');

jQuery plugin for Facebook "Like" Button

On lots of sites now, you can see a Facebook "Like" Button.
- When depressed, it changes background color.
- When mouse-overed, it allows you to write some additional text
I love this interface - lightweight action, but allow for expression of more data if the user wants to.
Anyone has written a similar plugin?
UPDATE:
See: http://www.engadget.com/2010/05/30/htc-evo-4g-gets-hacked-froyo-port-sense-ui-be-damned/ at the bottom of a post, you will see the facebook like button
I don't know of such a plugin for jQuery, but writing the user-interface is quite simple.
(Edit: Actually I just thought of a place where I could use this feature myself. I might just as well write a proper plugin based on this next week if I have the time, and edit it here. For the time being, below is what I originally posted...)
All you need is a couple of divs:
<div id="thebutton">Click me!</div>
<div id="thebox" style="display:none;">Content goes here</div>
And some jQuery:
<script type="text/javascript">
$(function () {
$('#thebutton')
.click(function () {
//Show/hide the box
$(this).toggleClass('activated');
$(this).hasClass('activated') ? $('#thebox').fadeIn() : $('#thebox').fadeOut();
})
.mouseenter(function () {
//If the button is .activated, cancel any delayed hide and display the box
$(this).addClass('hovering');
if ($(this).hasClass('activated')) {
$('#thebox').clearQueue().fadeIn();
}
})
.mouseleave(function () {
//Hide the box after 300 milliseconds (unless someone cancels the action)
$(this).removeClass('hovering');
$('#thebox').delay(300).fadeOut();
});
$('#thebox')
//When hovering onto the box, cancel any delayed hide operations
.mouseenter(function () { $(this).clearQueue(); })
//When hovering off from the box, wait for 300 milliseconds and hide the box (unless cancelled)
.mouseleave(function () { $(this).delay(300).fadeOut(); });
});
</script>
The rest is pretty much just CSS for #thebutton, #thebox, .hovering and .activated.
Here's a spartan look I used while writing this:
<style type="text/css">
#thebutton { width: 100px; background-color: #eee; text-align: center; padding: 10px; cursor: pointer; }
#thebutton.activated { font-weight: bold; }
#thebutton.hovering { color: Blue; }
#thebox { background-color: #eee; position:relative; width: 300px; height: 200px; padding: 10px; top: 5px; display: none;}
</style>
How about this jquery plugin: http://socialmediaautomat.com/jquery-fbjlike-js.php
It's really simple to set up and lets you perform some neat tasks in combination with the jquery cookie plugin (have a look at the demo page).
You can handle the hover, mousedown, and mouseup events and change the button's content or style.
Is not a plugin it uses the Facebook Javascript SDK. You load it by placing this at bottom of your document:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
Add this attribute to your HTML tag(the actual HTML tag right after the DOCTYPE):
xmlns:fb="http://www.facebook.com/2008/fbml"
And then you can place this snippet wherever you want a Like button:
<fb:like></fb:like>
Using the $('#your-button').button(); function from the jQuery UI library gives this functionality, and a whole lot more.
http://jqueryui.com/themeroller/

Resources