Angularjs selector with attribute - javascript

I need to make something like that:
function keyupHandler(keyEvent){
angular.element('div.keyFriendly[key='+keyEvent.key +']').click();
}
But it doesn't work. I get an error if I use angular.element(document.querySelector('div.keyFriendly[key='+keyEvent.key +']'))
I can make something like this:
function keyupHandler(keyEvent){
let mass = angular.element(document.querySelectorAll('div.keyFriendly'));
for(let i=0;i<mass.length;i++){
if(mass[i].attributes.key.value==keyEvent.key) mass[i].click();
}
}
And this fulfills my needs. But I hope there is some way to make it more short and simple, NO?

The problem is that you're not assigning the attributes value inside a string.
What you want is:
function keyupHandler(keyEvent){
angular.element('div.keyFriendly[key="'+keyEvent.key +'"]').click();
}

Related

Acessing value of variable in callign method in Javascript

I am learning in javascript and i want to solve this:
var text = "element1";
function OpenOrClose (text){
CKEDITOR.instances.text.getData();
}
I just want to replace text in calling method in function by value of variable text (in this case element1). I also read something about eval('text') and window['text'], but when i tryed to use it like this:
CKEDITOR.instances.eval('text').getData();
It wasn't work.
Thank you for your help
Attributes = items etc.
CKEDITOR.instances[text].getData();

html "data-" attribute as javascript parameter

Lets say I have this:
<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this.data.uid, this.data-name, this.data-value)">
And this:
function fun(one, two, three) {
//some code
}
Well this is not working but I have absolutely no idea why. could someone post a working example please?
The easiest way to get data-* attributes is with element.getAttribute():
onclick="fun(this.getAttribute('data-uid'), this.getAttribute('data-name'), this.getAttribute('data-value'));"
DEMO: http://jsfiddle.net/pm6cH/
Although I would suggest just passing this to fun(), and getting the 3 attributes inside the fun function:
onclick="fun(this);"
And then:
function fun(obj) {
var one = obj.getAttribute('data-uid'),
two = obj.getAttribute('data-name'),
three = obj.getAttribute('data-value');
}
DEMO: http://jsfiddle.net/pm6cH/1/
The new way to access them by property is with dataset, but that isn't supported by all browsers. You'd get them like the following:
this.dataset.uid
// and
this.dataset.name
// and
this.dataset.value
DEMO: http://jsfiddle.net/pm6cH/2/
Also note that in your HTML, there shouldn't be a comma here:
data-name="bbb",
References:
element.getAttribute(): https://developer.mozilla.org/en-US/docs/DOM/element.getAttribute
.dataset: https://developer.mozilla.org/en-US/docs/DOM/element.dataset
.dataset browser compatibility: http://caniuse.com/dataset
If you are using jQuery you can easily fetch the data attributes by
$(this).data("id") or $(event.target).data("id")
The short answer is that the syntax is this.dataset.whatever.
Your code should look like this:
<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset.uid, this.dataset.name, this.dataset.value)">
Another important note: Javascript will always strip out hyphens and make the data attributes camelCase, regardless of whatever capitalization you use. data-camelCase will become this.dataset.camelcase and data-Camel-case will become this.dataset.camelCase.
jQuery (after v1.5 and later) always uses lowercase, regardless of your capitalization.
So when referencing your data attributes using this method, remember the camelCase:
<div data-this-is-wild="yes, it's true"
onclick="fun(this.dataset.thisIsWild)">
Also, you don't need to use commas to separate attributes.
HTML:
<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this)">
JavaScript:
function fun(obj) {
var uid= $(obj).attr('data-uid');
var name= $(obj).attr('data-name');
var value= $(obj).attr('data-value');
}
but I'm using jQuery.
JS:
function fun(obj) {
var uid= $(obj).data('uid');
var name= $(obj).data('name');
var value= $(obj).data('value');
}
you might use default parameters in your function
and then just pass the entire dataset itself, since the
dataset is already a DOMStringMap Object
<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset)">
<script>
const fun = ({uid:'ddd', name:'eee', value:'fff', other:'default'} = {}) {
//
}
</script>
that way, you can deal with any data-values that got set in the html tag,
or use defaults if they weren't set - that kind of thing
maybe not in this situation, but in others, it might be advantageous to put all
your preferences in a single data-attribute
<div data-all='{"uid":"aaa","name":"bbb","value":"ccc"}'
onclick="fun(JSON.parse(this.dataset.all))">
there are probably more terse ways of doing that, if you already know
certain things about the order of the data
<div data-all="aaa,bbb,ccc" onclick="fun(this.dataset.all.split(','))">

how to pass a function name via JSON and call it in javascript/jQuery?

I have a JSON string which includes a function I need to call.
My JSON looks like this:
{
"type":"listview",
// the function I would like to call
"content":"dynoData.getRetailers()",
"custom_classes":["","nMT pickList","",""],
"lib":"static_listview.html",
"tmp":"tmp_listview_inset",
"lang":"locale_search",
...
I'm using this to assemble a jQuery Mobile listview on the client. To get the dynamic data, I need to call dynoData.getRetailers().
However I'm struggling to make the call :-)
This is what I'm trying:
var dyn = $.parseJSON( passed_JSON_string ),
content = dyn.content;
I had hoped calling it would trigger the function but it just returns the function name as a string.
Question:
How can trigger the actual function?
Thanks!
EDIT:
I'm putting the JSON string on the HTML element on the actual page, which I will replace with the element I'm building. Here is the HTML:
<ul data-template="true" data-config='{
"type":"listview",
"content":"dynoData.getRetailers()",
"custom_classes":["","nMT pickList","",""],
"lib":"static_listview.html",
"tmp":"tmp_listview_inset",
"lang":"locale_search",
"theme":"c",
"filter":"true"
}'></ul>
I could put all of these into data- attributes, but that would be messy...
Solution:
This worked:
1) change JSON to:
..."method":"getRetailers", ...
2) call from Javascript:
content = dynoData[ dyn.method ]();
Thanks everyone!
Assuming the function is always part of the dyn object you can use notation like following to call a function:
dyn['dynoData']['getRetailers']();
So if you are able to adjust json you could send back something like:
"content":{ "mainObject": "dynoData" , "method" :"getRetailers"}
And translate it to your dynamic function using variables:
dyn[content.mainObject][content.method]();
As an example using jQuery try using the following :
$('div')['hide']();
Which is the same as :
$('div').hide()
As charlietfl pointed out you can use object notation to call functions. For your case you have to get rid off () and split it, then call it like this;
jQuery(function($) {
var temp = $('ul').data('config').content.replace(/\(\)/g, '').split('.');
window[temp[0]][temp[1]]();
});
However this could solve your problem, if you think about future, you have to extend it a little bit. This way even you don't know the depth, you can call it anyway;
jQuery(function($) {
var temp = $('ul').data('config').content.replace(/\(\)/g, '').split('.'), func, i, il = temp.length;
for(i = 0; i < il; i++) {
if(func == null) {
func = window[temp[i]];
continue;
}
func = func[temp[i]];
}
func();
});
Try ConversationJS. It makes dynamic calls pretty easy and its a great way to decouple your codebase: https://github.com/rhyneandrew/Conversation.JS
JSON is purely data notation to be passed around so it is easily read and parsed, therefore it has no concept of functions. However, there are other ways of dealing with this and if you are starting to think that that is the only way to deal with your dilemma, then take a step back and examine your design. Instead of using this:
eval(yourCode);
Try this
var tempFun = new Function(yourCode);
tempFun();

Is it possible to pass variables to jquery's css function?

I'd like to set css of a div element dynamically using jQuery css() function instead of using string literals/ string constants for the css() function. Is it possible?
Instead of using the following codes with string literals:
$('#myDiv').css('color', '#00ff00');
I would like to use variables to set css for #myDiv element like
Version 1:
var propertyName = get_propery_name(myVariable1); // function get_propery_name() returns a string like 'background-color'
var value = get_value(myVariable2) ; // function get_value() returns a string like '#00ff00'
$('#myDiv').css(propertyName, value);
Version 2: (just hard coded to see if they work without calling custom functions like version 1 above):
var propertyName = 'background-color';
var value = '#00ff00';
$('#divLeftReportView').css(propertyName, value);
Both variable versions of codes do not work. Please help. Thanks.
Both of your examples will work just fine. I would suggest just a bit cleaner approach (personal syntax preference):
$(document).ready(function () {
$('#myDiv').css(get_propery_name(myVariable1), get_value(myVariable2));
}
Here's a working fiddle.
If you want to take it a step further, you can return a CSS map instead of strings:
$('#divLeftReportView').css(GetCssMap("foo"));
function GetCssMap(mapIdentifier) {
return { "background-color" : "#00ff00" }
}
Here's a working fiddle.
The code you posted here should work. I have done both versions of what you are trying to do several times. If it is not working, there is a good chance that something is wrong somewhere else in your javascript OR that you do not have the correct selector/id for the element(s) which you want to change.
Try adding alert("test"); immediately after $('#divLeftReportView').css(propertyName, value);. If you get the popup saying "test" then the problem is with your selector. If not, then the problem is a bug in your javascript.
Also try adding $('#divLeftReportView').css("background-color", "#00ff00"); in the same place. That will confirm whether or not the selector is working.
Seems to work fine at http://jsfiddle.net/gaby/6wHtW/
Make sure you run your code after the DOM ready event..
$(function(){
var propertyName = 'background-color';
var value = '#00ff00';
$('#divLeftReportView').css(propertyName, value);
});
otherwise your elements might not be present in the DOM..
You can also pass multiple CSS parameters within one variable as an array:
$(function(){
var divStyle = {'background-color': '#00ff00', 'color': '#000000'}
$('#divID').css(divStyle);
});
yes, using jQuery attr method you can change css dynamically
var height=$(".sampleClass1").innerHeight();
$('.sammpleClass2').attr('style', 'min-height:'+height+' !important');

jquery selector for multiple classes

I have elements in my DOM with class="LiveVal:variablepart" and i would like to write a JQuery selector that works even if the elements have other classes on tom of the above. Eg. class="header LiveVal:varablepart" or class="LiveVal:varablepart header".
It works fro me if LiveVal is the first class with:
$('[class^=LiveVal:]').each(function ( intIndex ) { somefunction });
but obviously not if another class is before LiveVal.
In the function I need to extract the variable part. I planned to do like this:
theclass = $( this ).attr('class');
varpart = theclass.replace('\bLiveVal:(.+?)[\s]', '$1');
..but alas, it doesn't match. I've tested the regex on http://gskinner.com/RegExr/ where it seems to work, but it doesn't in javascript !?
Any help would be greatly appreciated.
This will check if a class name contains 'LiveVal:'
$('[class*=LiveVal:]').each(function ( intIndex ) { somefunction });
EDIT
did not realise you had that requirement (although a good one). You can do this instead: $('[class^="LiveVal:"], [class*=" LiveVal:"]')
Here is a fiddle: http://jsfiddle.net/wY8Mh/
It might be somewhat faster to do this with an explicit filter:
$("*").filter(function() { return /\bLiveVal:/.test(this.className); }).something();
It depends on whether the native "querySelectorAll" does the work, and does it quickly. This also would avoid the "FooLiveVal" problem.
It's worth noting that in an HTML5 world, it might be better to use a "data-LiveVal" attribute to store that "variable part" information on your elements. Then you could just say:
$('[data-LiveVal]').something();
In the HTML, it'd look like this:
<div class='whatever' data-LiveVal='variable part'>
Since version 1.5, jQuery will fetch stuff in a "data-foo" attribute when you pass the tail of the attribute (the part after "data-") to the ".data()" method:
var variablePart = $(this).data('LiveVal');
The ".data()" method will not, however, update the "data-foo" property when you store a new "variable part".
edit — if you want the value that's stuffed into the class after your property name prefix ("LivaVal:"), you can extract it like this:
var rLiveVal = /\bLiveVal:(\S*)\b/;
$('*').filter(function() { return rLiveVal.test(this.className); }).each(function() {
var variablePart = rLiveVal.exec(this.className)[1];
//
// ... do something ...
//
});
(or some variation on that theme).

Categories

Resources