How to find a div has a widget in Jquery? - javascript

How to check if the div has the widget or not ? for eg.
if we add a class to div we can check that using .hasClass like this, is there is any way to find widget is exists or not?

You're question is very difficult to understand. Since you've provided no code or explanation about your custom widget, it's also very difficult to answer. Based on your limited information, this is the best I can do...
Assign a CSS class to your widget (e.g. clsWidget). If the widget always has the clsWidget class, you can check for its existence like this:
if($("[DivThatMightContainWidgetSelector]").find(".clsWidget").length > 0) {
//Div contains widget
}
else {
//Div does not contain widget
}

If you want to know if a div is currently used as a jQuery UI widget (which may be what you're asking, though I'm not entirely sure), you can check if the div has the "ui-widget" class.
$("yourDivSelector").hasClass("ui-widget")
Every jQuery UI widget has this class, and I believe most well-implemented third-party widgets use this class too (part of the CSS framework of jQuery UI).

The standard method to check if a widget was assigned to a tag, without checking if the tag has a widget class, is...
if ( !($("#myInput").data( "ui-fooWidget" ) )
< widgetNotFound >
else
< widgetFound >
Its a useful routine if you want to assign a different widget on certain devices, or to check if the widget has been initialised before calling a widget method etc.
All ui-widgets will store the root widget object in the data object assigned to the tag. This is also a used to access private widget methods.

Related

Applying a javascript function on a div

I want to put a variable on a div and to be applied and inherited by all the dojo widgets under this div.
Is this feasible ?
For example
<div shaper="Contextual">
<textarea ..../>
<select multiple data-dojo-type="dijit/form/MultiSelect">
....
</div>
I want the functionality supported by the shaper to be applied to all the widgets included in the div.
p.s.: "shaper" is a custom module created to do numeric shaping for Arabic numbers.
It's possible, but not out of the box.
You can write something like this:
require(["dojo/query", "dojo/domReady!"], function(query) {
query("[shaper]").forEach(function(shaper) {
});
});
This will query all elements with a shaper attribute and loop over it. Inside the loop, you will have to retrieve the value of the shaper attribute (for example Contextual), you can do that with the getAttribute() function, for example:
var shaperModule = shaper.getAttribute("shaper");
Now you have the name of the module to load, so you can write something like this inside the loop:
require([shaperModule], function(shaperModule) {
});
This will use AMD to retrieve the Contextual module. Now all that's left is to include the shaper functionality into all widgets inside your <div>.
First of all, with dijit/registry::findWidgets() you can retrieve all widgets inside a specific DOM node, you can use this to retrieve your dijit/form/MultiSelect widget in this case:
registry.findWidgets(shaper);
Then you can loop over the array of widgets that are found and use dojo/_base/lang::mixin() to extend an object with the contents of another object, for example:
registry.findWidgets(shaper).forEach(function(widget) {
lang.mixin(widget, shaperModule);
});
For example: http://jsfiddle.net/zLv7cvzt/
Though this might not work entirely (what if the module does not exist or what about widgets inside widgets, which dijit/registry::byId() does not detect), it does give you an idea of how to achieve it.
To answer your second question, if it's feasible or not, I would say that it depends. If you extend a widget with another widget like this, it could really end up with really weird things, because all widgets extend from dijit/_WidgetBase, which provides the widget lifecycle, you could mix both widgets their lifecycle.
Also, if you end up doing this and you get an error, it will be really hard to debug this if you're not familiar with the custom code.

add attribute to DOM element

I have a modal form that is generated using bootstrap 3. It doesn't look like there is a reliable way to determine when that form is being shown onscreen. I am attempting to create one. I attached two events to my DOM element that signal when it is shown and when it is hidden.
jq_modal_login_form = $('#modal-login-form')[0]
jq_modal_login_form.on('shown.bs.modal', function () {
jq_modal_login_form.active_onscreen = true;
});
jq_modal_login_form.on('hidden.bs.modal', function () {
jq_modal_login_form.active_onscreen = false;
});
I tried to give an attribute named active_onscreen to the DOM element above. When I look at the DOM element in the debugger later, the attribute is not present.
I should mention that I am VERY new to javascript. Is attribute even the right word to use here? It looks like attribute is a bit of a misnomer as well. It could be an attribute of the object but could also be an attribute of the object.attributes attribute, right? I assume the later is where styling ect., goes and is not what I want to change. Does anyone have some insight as to what I should be doing here?
In jQuery:
$('selector').attr('attribute_name', 'value');
However, you can should only use predefined attributes as creating custom attributes requires additional setup (see this question) that is not necessary in your case.
In your case, you may just want to add a active_onscreen class to the element. Classes are meant to be used to identify elements (and not just for CSS), so they are perfect for this applicaiton. You would use this to add a class to an element:
$('selector').addClass('active_onscreen').
When it is no longer active, you would use this to remove the class:
$('selector').removeClass('active_onscreen').
What you are doing here is adding a property of the DOM object - not an attribute of the element.
Adding an attribute does not necessarily make the property mirror it. Only built-in properties do this.
If you want to set an attribute, but not the property, you can use jQuery's .attr() method.
If you just want to see if a given modal is open, Bootstrap does that for you. You can check the bs.modal data attribute:
$("element").data('bs.modal').isShown;
or a class (but this method is prone to race conditions):
$('#myModal').hasClass('in');

Initialize multiple js controls by searching DOM only once

I would like a function that initializes all of my javascript/jquery controls (date pickers, sliders...).
This is mostly done using a class attribute to identify on which element to initialize the control.
Currently, I'm using a jQuery selector to get the elements.
If I understand correctly, every time I use a selector I'm searching the whole page. So if I have 10 controls and one selector for each control type, I will search the whole page 10 times.
Could there be a way to search the page only once ?
The idea would be to have a collection of css class names with the corresponding initialization method to call. Go through the page only once, and on each element if I find a corresponding class, call the initialization.
Hope I'm being clear enough.
hope this helps. The approach I would suggest would be to apply a class to every item that you want initialized, lets say "initializeMe" and then have specific classes for datepicker etc.
$(function(){
$(".initializeMe").each(function(){
if($(this).hasClass("className")){
// lets say the class name is datepicker and you initialize datepicker here.
}
});
});
Could you give each one of those elements the same class and use the .each() method?
For example:
$('.canInitialize').each(function(){
Initialize($(this));
});
I don't know whether that prevents the DOM search every time or not.

How to name a Javascript Function specific to id of a div encapsulating it in ASP.NET MVC

I have a partial View, which I am trying to load twice onto a cshtml file.
Now inside my partial View I have a javascript function as well. At this point, when I load my
cshtml onto the page, I will have two Javascript functions with same name.
I want to avoid this kind of scenario and name the Javascript function uniquely depending upon the Model which I am binding the Partial View to.
Please Not I could achieve the uniqueness for each control inside my partial by associating it with a parameter like "#Model.Id". But I am unable to apply the same kind of thing for uniqueness of Javascript function.
I am sorry for my Bad English. Kindly let me know if you need additional details.
Instead of having many functions with different names for each partial you could have a single javascript function which operates on each control. So for example you could assign a class to those controls and then write your function under the form of a jQuery plugin attached to all controls with this classname.
Now the function could be declared inside a separate javascript file without mixing markup and javascript in a partial which is a bad design. The plugin could then be simply attached to all controls with this class with a standard jQuery syntax:
$(function() {
$('.someClass').myFunction();
});
You could also use the HTML5 data-* attributes on your DOM elements to associate some metadata with them such as an unique identifier coming from your model. This metadata will then be accessible in your jQuery plugin.
For example:
<div class="someClass" data-id="#Model.Id">
This is some div with associated metadata
</div>
In order to achieve scenario like that you can use data-attribute.
For example we have identical html code surrounded by a div, those div's had different id.
Each div will have a data-attribute and with jquery you can catch an event (Like Click)
Now Code Example
HTML
<div id="id1" data-attribute="doSomething">Element</div>
<div id="id2" data-attribute="doSomething">Element</div>
In your case those div represent the results coming from the partial view
also you can change the value store in the id attribute to come from your model something like id="id#{Model.Id}"
JQuery
$("div[data-attribute=doSomething]").click(function() {
alert("Clicked element: " + $(this).prop("id"));
});
Fiddel Example
I am using attribute selector of Jquery to achieve it
Note That you can achieve it also by defining a class attribute.
But I think you should use this when you actually need a class otherwise use custom attribute like data-value="something"

CKEditor: Class or ID for editor body

I have an instance of CKEditor on a page. I am trying to give the CKEditor's body a class or ID so it matches some styles I have defined in a stylesheet.
There is a API documentation that should give access to the respective DOM elements, but I can't seem to get it working. All objects I try to query that way turn out undefined.
Does anybody know how to do this, or how to properly address CKEditor's dom elements?
Edit: Thanks folks, nemisj's answer did it for me but for some reason, I don't get to set the "accepted" checkmark in this question.
Although that part of the API wasn't ported from 2.x at the time that this question was placed, now it's easier to use the bodyId and bodyClass config options.
Of course, the explanation by nemisj is good and can be useful for other things, but you must remember that each time that you switch away from design (to source view), the iframe is destroyed, so you'll need to reassign your attributes if you do it manually.
If you are talking about CKEditor( version 3), then there is a possibility to get any DOM instance inside the editor itself. Every CKEditor instance has reference to it's document via "document" property.
var documentWrapper = edit.document;
This reference represent some public wrapper for all CKEditor nodes, but it also has the direct reference to its node. You can retrieve by getting ["$"] property.
var documentNode = documentWrapper.$; // or documentWrapper['$'] ;
documentNode will represent the DOM instance of the document node inside the iframe. After you have the DOM instance, you can do whatever you want to do with DOM structure, Append, remove, replace classes, rebuild, etc. For example
documentNode.body.className = "zork";
I hope this should be enough.
I had the same problem today in trying to set the bodyClass like this:
CKEDITOR.replace( 'editor1',
{
fullPage : true,
bodyClass : 'myClass'
});
What I found is that in this version (3.3.1), if you set fullpage = true, setting the bodyId or bodyClass does not work, but if you set fullPage = false, it does work.
Hope this helps.
From the Manual:
<static> {String|Array} CKEDITOR.config.contentsCss
The CSS file(s) to be used to apply style to the contents. It should reflect the CSS used in the final pages where the contents are to be used.
config.contentsCss = '/css/mysitestyles.css';
config.contentsCss = ['/css/mysitestyles.css', '/css/anotherfile.css'];
Default Value:
<CKEditor folder>/contents.css
Don't know that editor, but as they all work the same way, you probably can't access the DOM elements created by the instance because they are created after the page has finished loading, and the DOM is ready as well. So, any new DOM elements added after that, theorically will not exist.
Still, you can try TinyMCE editor, wich has a "partnership" with jQuery javascript library to manipulate all you want, and the editor itself is pretty easy to change in almost every way.
Your queries may return undefined because the editor instances are placed inside an iFrame and your query is not looking there?
In config.js, write this code
config.bodyId = 'contents_id';
then you see body id in Ckeditor but when you want to access this id please use
$('#parent_id').find('iframe').contents().find('#within_iframe')
there $('#parent_id') means form_id or any parent which is simply way to access iframe. follow this code to access element in iframe

Categories

Resources