Write a function from native javascript to jQuery [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm wondering how can I rewrite this javascript function into jQuery but using if/else statements instead of while:
<textarea style="overflow-y: hidden;" onkeyup="expandtext(this);"></textarea>
function expandtext(textArea){
while (textArea.rows > 1 && textArea.scrollHeight < textArea.offsetHeight) {
textArea.rows--;
}
while (textArea.scrollHeight > textArea.offsetHeight) {
textArea.rows++;
}
textArea.rows++
}

Well, since you appear to want it so badly, here it is
$.fn.expandText = function () {
$.each(this, function (k, textArea) {
while (textArea.rows > 1 && textArea.scrollHeight < textArea.offsetHeight) {
textArea.rows--;
}
while (textArea.scrollHeight > textArea.offsetHeight) {
textArea.rows++;
}
textArea.rows++
});
}
$('textarea').expandText();
FIDDLE
Additionally, I think I understand what you wanted to ask. In order to understand this you need a good understanding of javascript objects and document object model. There are special properties of objects in the DOM which affect how the objects are displayed (this is all done by your browser automatically), rows is one of those properties, and in order for the element on the page to change in height, which is the goal of this function, you need to change the property rows on the specific element. You can't do this with jQuery (or maybe you can, who knows) because it wraps your object in other objects. Even if it is possible, you are going to have to call a function on the wrapper object which is then going to access the DOM object and change it's property, which is what your function does in the first place, so why bother at all.

Related

How to run an event function once [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a lot of questions its all on java script (with some jquery)
first im trying to detect the mouse X cordinates when the mousemove on an element :
(function() {
'use strict';
$('.AnyElement').mousemove(function (e) {
console.log(e.pageX)
});
})();
i want to detect the mouse X once i know theres a functions like mouseover etc...
but in general how to make this function run once and stop
Second when someone write :
if (document.body = 1) {
// do anything
}
he is checking if document.body equal to 1
i see a thing in someone else code i dont undertand here it is :
if (document.body) {
// do anything
}
it doesnt matter what the function do , the thing is what he is checking ???
In answer to your first question there are a few ways you could do it, one example would be to register the mousemove event and then remove the event after logging it once.
$('html').mousemove(function(e) {
console.log(e.pageX);
$('html').off('mousemove');
})
Another method could be use the one event listener built into jQuery.
$('html').one('mousemove',function(e) {
console.log(e.pageX);
});
In answer to your second question the first statement is looking for the length of the element, if the element exists it will generally be greater than 0. In the second statement document.body will return a boolean of true or false depending on whether or not the element exists. Again there are a million different ways you can do the same thing in Javascript.
Hope that helps!

Is it bad to have If-instanceof-statements in Typescript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
selectAction: (actionEvent) => {
if (actionEvent instanceof Action1) {
// action1 body implementation
} else if (actionEvent instanceof Action2) {
// action2 body implementation
}
}
The above code snippet reflects that different types of action which does different functionalities.I have used if and else condition to check action.
I feel it's not a good solution since I might have more actions in the future and my if-else-ladder will keep growing and I need to update my code again when there is a change.
Any idea on improving this specific scenario?
Use the approach of duck typing to avoid conditional scenarios. Source
Have a method called selection() inside each type instance Action1 and Action2 so- on and use that to define the body/desired functionality you want to build. And simply call selection() method avoiding condition. So based on the instance of the type it will call the correct selection() method of the corresponding type
There's nothing inherently wrong with using if/else in TypeScript.
However, when you're using instanceof, the odds are that you probably have a better option available. In this case, almost certainly, the actions themselves should be responsible for doing what they do:
selectAction: (actionEvent) => {
actionEvent.execute();
}
...or
selectAction: (actionEvent) => {
const action = /*...derive action from actionEvent...*/;
action.execute();
}
...or similar (or of course, use actionEvent.execute() directly instead of selectAction).
This is fundamentaly polymorphism, having different objects conforming to the same interface, and doing (potentially) different things when called.

adding second to my JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hello how can I add a second portion to my javascript. Here is the code:
var $pagerT = $('<div class="pager"></div>');
var $pagerB = $('<div class="pager"></div>');
for (var page = 0; page < numPages; page++) {
$('<span class="page-number"></span>').text(page + 1).bind('click', {
newPage: page
}, function(event) {
currentPage = event.data['newPage'];
$table.trigger('repaginate');
$(this).addClass('active').siblings().removeClass('active');
}).appendTo($pagerT).addClass('clickable');
}
Basically I want to add the same class that was added to $pagerT to $pagerB. Here is the code:
}).appendTo($pagerT, $pagerB).addClass('clickable');
Any subjections on how I can process it?
You can use .add
$pagerT.add($pagerB).addClass('clickable');
I'm going to say
var $pagers = $pagerT.add($pagerB);
...
}).appendTo($pagers);
$pagers.addClass('clickable');
The docs say that the argument to appendTo() can be an array of elements, and in that case, "cloned copies of the inserted element will be created for each target after the first".
(However I'm not sure if $pagerT.add($pagerB) creates an array (the doc says it creates a set); or more to the point, whether this value is acceptable as an argument to appendTo(). Testing this is left as an exercise to the reader.)
Or if you value brevity over maintainability,
...
}).appendTo($pagers.addClass('clickable'));
That's assuming that you want to add the <span> to both $pagerT and $pagerB (which you didn't say, but your second code example suggests) and add the 'clickable' class to both (which you said but which conflicts with your original code).

How to apply substring to every letter in array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm making an array of textstrings like this:
phone = $(data).find('.tel a')
I would like to apply a substring(8) to every item in the array called phone. Is a for-loop the best way to do it?
phone, as it stands, contains a jQuery object, which is an Array-like Object of DOM elements. If you want to iterate over all of them and get their inner text, applying .substring(8) to each, and building an array out of them, you can use something like this:
var phoneArray = $(data).find(".tel a").map(function (i, el) {
return $(el).text().substring(8);
}).get();
DEMO: http://jsfiddle.net/96HWv/
(in the demo, I had to emulate what data could be, although I'm guessing it is an HTML string in your real code)
You can use the map() method :
phone = phone.get().map(function(e) { return $(e).text().substring(8) });
FIDDLE
You can use the .each() function for this... Something like:
$(data).find('.tel a').each(function() {
$(this).text(function(index,text) {
return text+"substring(8)";
});
});
You can let jQuery do the work for you.
$(data).find('.tel a').addClass('substring');
jQuery will traverse the array of elements returned and add the class to all of them.

creating DOM nodes from arrays [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Note: This is a continuation of another question that I decided were two separate issues that need to be solved. I'm also currently not sure of how exactly to phrase this question, so I will try my best and when I get more clarity I will rephrase my question for future reference.
I'm writing two basic jQuery plugins, $.fn.query and $.fn.build, that sort an array, and create html code to insert into a document, respectively. I'm currently testing it with Vimeo video ID's that I will display videos with.
$.fn.build has three parts. First it wraps every array item with individual containers, the builds them into rows (problem area), then lastly it wraps everything in a container. (every part of this is optional).
Specifically the problem comes from this line: $(tmp).add(newRow); although it is valid javascript.
if ( options.splitBy !== undefined && options.wrapRow !== undefined ) {
var tmp = $([]),
newRow = function(i) {
$(build.splice( i, i + options.splitBy )).wrapAll( options.wrapRow ).parent();
};
for (var i = 0, l = build.length, a = options.splitBy; i < l; i += a) {
$(tmp).add(newRow);
}
build = tmp;
console.log(build);
}
See: http://jsbin.com/upatus/2/edit
I am quite sure that you want to use the function, instead of adding the function itself. Also, you will want to use the same tmp object all over the time, instead of wrapping it into a new jQuery instance and not adding to the original one. Try
tmp.add(newRow(i));
BTW: If you want to build an array, you should use
var tmp = [];
and
tmp.push(…);
Now I've looked at the code from the other question. Both answers are correct, and contain some valid points:
splice is an Array function on jQuery's prototype, and returns an array. (You have fiexd this now)
Your query method returns an array, but should return a jQuery instance for chaining
Your build variable was not initialized, but used
You should really choose whether you want to use arrays or jQuery objects internally in your function, and not mix them.
BTW, you should rename your functions to more descriptive names. "build" and "query" are very vague and may collide with other plugins.

Categories

Resources