How to get data-icon from anchor tag? - jquery-mobile

I have this HTML:
<div id="measureControl" data-role="controlgroup" data-type="vertical">
</div>
When anchor clicked I need to get data-icon attribute and to set another data-icon (for example eye).
I try this:
$("#measureButton").click(function () {
var el = $(".ui-icon", this);
var output = document.getElementById('output');
if (el.hasClass("home")) {
el.removeClass("home");
el.addClass("eye");
output.style.display = "block";
} else {
measureControls.line.deactivate();
el.removeClass("eye");
el.addClass("home");
output.style.display = "none";
}
});
But it doesn't work.
Any idea how can I implement it using jQuery or JavaScript?

just use jquery .data function
$("#measureButton").click(function () {
var currentIcon = $(this).data('icon');
alert(currentIcon);
$(this).data('icon','eye');
var currentIcon = $(this).data('icon');
alert(currentIcon);
});
https://jsfiddle.net/qs9zwwo0/

user jquery attr function to get the attributes value.
$("#measureButton").click(function () {
//to get the data icon.
alert($(this).attr('data-icon'));
// to set data icon
$(this).attr('data-icon','eye');
});

Is very simple with pure JavaScript.
var iconData = measureButton.dataset.icon;

Like Tushar indicated:
$(document).on("click", "#measureButton", function(){
$(this).attr("data-icon", "eye").button( "refresh" );
});

Related

Jquery data-role collapsible events aren't being captured in Jquery Mobile

Could anybody please let me know why the following code isn't working when i am using with Jquery mobile JS
http://jsfiddle.net/znz17ctm/7/
This is my code
<div role="main" class="ui-content oms-content" id="dd">
<div class="myactivelabelsWrap" id="result"></div>
</div>
var response = {
"Restaurants": [{
"RestrntArea": "Haii",
"cust_loc_id": "374"
}, {
"RestrntArea": "rerrrwe",
"cust_loc_id": "373"
}]
}
showLabels();
function showLabels() {
//$("#result").html("");
var favoriteresultag = '';
for (var i = 0; i < response.Restaurants.length; i++) {
var name = response.Restaurants[i].RestrntArea;
if (name) {
favoriteresultag +=
'<div data-role="collapsible" data-inset="false" class="my-collaspible"><h3>' +
name +
' <a class="icon-pencil-1 labelEditIcon "></a></h3></div>';
}
}
$("#result").append(favoriteresultag).trigger("create");
}
$(document).ready(function() {
$('.my-collaspible').bind('expand', function() {
alert('Expanded');
});
$('.my-collaspible').bind('collapse', function() {
alert('Collapsed');
});
});
Why the collapse and expand even'ts are being captured ??
Instead of document ready i tried with al the page events of mobile . But no luck .
From your fiddle I can't tell which version of jQM you are using. You have checked version 1.3 but then added the 1.4 css. Assumin version 1.4, I have updated your fiddle:
FIDDLE
Basically, you need to use event delegation to attach the events because the collapsibles do not exist at the time of the bind. Also the event names are actually collapsibleexpand and collapsiblecollapse.
So use on() instead of bind() by handling the event on the parent div and delegating it to all items with class my-collapsible that exist now or added dynamically:
$("#result").on('collapsibleexpand', '.my-collaspible', function () {
alert('Expanded');
});
$("#result").on('collapsiblecollapse', '.my-collaspible', function () {
alert('Collapsed');
});

JQueryMobile: pagecontainershow on a particular page not working

JQueryMobile 1.4 has deprecated the pageshow event and instead recommends using pagecontainershow; however, while I'm able to get the pagecontainershow event at a document level, I can't bind a function to a particular page.
<div id="page1" data-role="page">
...
<script>
$( "#page1" ).on( "pagecontainershow", function( event, ui ) {
console.log("page1 pagecontainershow");
} );
</script>
</div>
Demonstration: http://jsbin.com/IFolanOW/22/edit?html,console,output
I also considered using the alternative form of the jQuery "on" function where we use a selector, but that would need to be a parent of the page div, and that might include other pages, so that doesn't work.
As a workaround, I've done this, but it is very inefficient:
function registerOnPageShow(pageId, func) {
var strippedPageId = pageId.replace("#", "");
var e = "pagecontainershow." + strippedPageId;
// TODO why isn't it working to use $(pageId) instead of $(document)?
$( document ).off(e).on(e, null, {page: strippedPageId, f: func}, function(e, ui) {
if ($(":mobile-pagecontainer").pagecontainer("getActivePage")[0].id == e.data.page) {
e.data.f(e, ui);
}
});
}
You can get the page ID like this.
$(document).on('pagecontainershow', function(e, ui) {
var pageId = $('body').pagecontainer('getActivePage').prop('id');
});
There is currently no way to have a show/hide event on a specific page.
Here is what I'm using (jqmobile >1.4):
$(document).on("pagecontainershow", function () {
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
var activePageId = activePage[0].id;
switch (activePageId) {
case 'loginPage':
...
break;
case 'homePage':
...
break;
case 'groupPage':
...
break;
default:
}
});
$(document).on("pagecontainershow", function(event, ui) {
var pageId = $('body').pagecontainer('getActivePage').prop('id'),
showFunc = pageId+'_show';
if (typeof MobileSite[showFunc] == 'function') {
MobileSite[showFunc]();
}
});
MobileSite is contained in an external .js file with all the show() functions.
$(document).on("pagecontainerbeforeshow", function (event, ui) {
if (typeof ui.toPage == "object") {
var crrentPage = ui.toPage.attr("id")
}
});
and you must use this code before calling Index.js !!

Direct URL to overlay on the page

I have an overlay on my page and I would like to give user a link / URL which leads them directly to the page, with the overlay loaded.
Is it possible to be done? How do I do that?
This is my code:
$(function() {
$('#overlay_job').click(function() {
document.getElementById('iframe_job').src = "http://targeturl-for-my-overlay-content";
$('#overlay_bg2').fadeIn('fast',function(){
$('#overlay_box').fadeIn('fast');
});
});
$('#boxclose').click(function() {
$('#overlay_box').fadeOut('fast',function() {
$('#overlay_bg2').fadeOut('fast');
});
});
var overlay_bg2 = $("#overlay_box");
//var top = $(window).scrollTop() - (overlay_bg2.outerHeight() / 2);
var top=0;
var left = -(overlay_bg2.outerWidth() / 2);
overlay_bg2.css({ 'margin-top': top,'margin-left': left });
if(getUrlVars()["openJobOverLay"] == "Y") {
$('#overlay_job').trigger('click');
}
});
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
===========
and on the page, user can click on this link to get the overlay shown:
<a id="overlay_job" class="underline" href="javascript:void(0);%20opener.jobframe.location.reload();">
See job openings
</a>
<img src="link_arrow.gif" class="linkarrow">
</div>
Hide the overlay with CSS: display: none;. Give the overlay element an id, then add the id to the URL like so http://www.yourpage.com#id. Then use jQuery to do something like this:
$(document).ready(function(){
if(window.location.hash) $('#' + window.location.hash).show();
});
Edit:
In your specific case add this line as the last line inside your $(document.ready();.
$(function() {
// All of your code inside this function...
if(window.location.hash) $('#' + window.location.hash).click();
});
function getUrlVars() {
// Some more of your code...

pass Ckeditor value to div text without html tags?

I have Ckeditor in my view and I dynamicly get editor value and show them in divs. I tried many combinaiton of defining(val,html,tex, etc) like this:
CKEDITOR.on('instanceCreated', function (e) {
e.editor.on('contentDom', function () {
e.editor.document.on('keyup', function (event) {
var str = CKEDITOR.instances['editor1'].getData();
$("#mirror1").text(str);
$("#mirror2").val(str);
$("#mirror3").html(str);
$('#mirror4').val($('<div/>').html(str).text());
}
);
});
});
my divs
<div id="mirror1">
</div>
<div id="mirror2">
</div>
<div id="mirror3">
</div>
<div id="mirror4">
</div>
for exaple When I wrote <pre>int i=0;</pre>
mirror1 text= <pre>deneme</pre>
mirror2 text= null
mirror3 text= <pre>int i=0;</pre>
mirror4 text= null
I m expecting output: int i=0;
How may I do this.What is the correct syntax?. Thanks.
If you skip the jQuery part, you can do it with simple javascript:
CKEDITOR.on('instanceCreated', function (e) {
e.editor.on('contentDom', function () {
e.editor.document.on('keyup', function (event) {
var str = CKEDITOR.instances['editor1'].getData();
document.getElementById("mirror1").innerHTML = str;
}
);
});
});
But using the DOM keyup event might not be enough if you want a good mirror, I suggest you to use the onChange plugin for CKEditor (disclaimer: I wrote it) and now the mirror will update whenever the content changes:
CKEDITOR.on('instanceCreated', function (e) {
var mirror2 = document.getElementById("mirror2");
e.editor.on('change', function () {
mirror2.innerHTML = CKEDITOR.instances['editor1'].getData();
});
});

How to create a dialog using jquery-ui without html div specified

Using jquery-ui to create a dialog is pretty easy:
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
...but one still needs a div in the HTML for this to work. In Dojo:
var dlg = new dijit.Dialog({
title:"dialog",
style: "width:30%;height:300px;"
});
dlg.show();
would just do the trick without anything specified in the html section, can jquery-ui do this? (I have to use jquery-ui here)
Thanks,
David
While I'm not sure why you would want to open a dialog with no content, you could easily create a new one on the fly and invoke the jquery dialog against it:
$("<div>hello!</div>").dialog();
basic code
var d = $("#someId");
if (d.length < 1)
d = $("<div/>").attr("id", "someId")
.appendTo("body");
else
d.dialog('destroy');
d.html('some message')
.dialog({ some_options })
.dialog("open");
and you can probably put rap this in an extension method.
Update (my full code listing)
(function($) {
$.extend({
showPageDialog: function (title, content, buttons, options) {
/// <summary>Utility to show a dialog on the page. buttons and options are optional.</summary>
/// <param name="buttons" type="Object">Dialog buttons. Optional, defaults to single OK button.</param>
/// <param name="options" type="Object">Additional jQuery dialog options. Optional.</param>
if (!buttons)
buttons = { "Ok": function () { $(this).dialog("close"); } };
var defOptions = {
autoOpen: false,
modal: true,
//show: "blind",
//hide: "explode",
title: title,
buttons: buttons
};
if (options)
defOptions = $.extend(defOptions, options);
var pd = $("#pageDialog");
if (pd.length < 1)
pd = $("<div/>").attr("id", "pageDialog")
.appendTo("body");
else
pd.dialog('destroy');
pd.html(content)
.dialog(defOptions)
.dialog("open");
}
}//end of function show...
)//end of extend Argument
})(jQuery)
Sample Usage
$.showPageDialog(title, message, {
"Yes": function () {
$(this).dialog("close");
// do something for 'yes'
},
"No": function () {
// do something for no
}
}
var div = document.createElement('div');
div.innerHTML = "Hello World";
$(div).dialog();
Juan Ayalas solution should work for modal Dialogs.
For a non modal dialog it would be better to track the id inside the function.
I use the following code which is not perfect but should work to ensure that the
id is unique. The code is nearly equal to Juan Ayalas example but uses a counter to avoid a duplicate id. (Furthermore I deleted the OK-Button as default).
(function($)
{
var dCounter=0; //local but "static" var
$.extend({
showPageDialog: function (title, content, buttons, options) {
/// <summary>Utility to show a dialog on the page. buttons and options are optional.</summary>
/// <param name="buttons" type="Object">Dialog buttons. Optional, defaults to nothing (single OK button).</param>
/// <param name="options" type="Object">Additional jQuery dialog options. Optional.</param>
if (!buttons)
buttons = {}; //{ "Ok": function () { $(this).dialog("close"); } };
var defOptions = {
autoOpen: false,
width: "auto",
modal: false,
//show: "blind",
//hide: "explode",
title: title,
buttons: buttons
};
if (options)
defOptions = $.extend(defOptions, options);
dCounter++;
//console.log("dCounter is " + dCounter);
var pdId = "#pageDialog"+dCounter;
var pd = $(pdId);
if (pd.length < 1)
pd = $("<div/>").attr("id", pdId)
.appendTo("body");
else
pd.dialog('destroy');
pd.html(content)
.dialog(defOptions)
.dialog("open");
}//end of function showPageDialog
}//end of extend options
)//end of extend argument
}//end of function definition

Resources