jQuery code need to translate to vanilla so I can use in Angular
I have this code on a template and I'm transfering the code to Angular 4 but it doesn't like the $ on jquery so I need a way to either be able to use it on Angular 4 or just translate it to pure js so I can use it.
Here's the code:
$('#toggle-btn').on('click', function (e) { e.preventDefault(); if ($(window).outerWidth() > 1194) { $('nav.side-navbar').toggleClass('shrink'); $('.page').toggleClass('active'); } else { $('nav.side-navbar').toggleClass('show-sm'); $('.page').toggleClass('active-sm'); } });
How can I do this?
2 answers
- answered 2017-08-16 19:29 Jim
Without adding the jQuery package:
declare var $: any;
and if you need typescript definition then add this package to your package.json
"@types/jquery": "^2.0.45",
- answered 2017-08-16 19:29 realdubb
How to do the same in vanillaJS.
function toggle(elements, className){ Object.keys(elements).forEach(element => elements[element].classList.toggle(className)) } function handleClick(e){ e.preventDefault(); if (window.outerWidth > 1194) { toggle(document.querySelectorAll('nav.side-navbar'), 'shrink'); toggle(document.getElementsByClassName('page'), 'active'); } else { toggle(document.querySelectorAll('nav.side-navbar'), 'show-sm'); toggle(document.getElementsByClassName('page'), 'active-sm'); } } document.getElementById('toggle-btn').addEventListener('click', handleClick);?
- Jquery - selecting parents with a data attribute
I am trying to select a parent which HAS an attribute of datalink
var url = $(e.target).parents(['data-link']).addClass('selected');
Is this possible?
- RegExp does not get replaced
I tested the regEx on RegExr and it's working but when I put it in my code nothing happens.
RegExp:
My Code:
$('.attachment-shop_thumbnail').each(function () { var imgsrc = $(this).attr('src'); imgsrc = imgsrc.replace('/-\d+x\d./g', ''); console.log(imgsrc); $(this).wrap('<a href="' + imgsrc + '" rel="lightbox"></a>'); });
I tried to put it in a new variable:
var rgx = new RegExp('/-\d+x\d./g'); imgsrc = imgsrc.replace(rgx , '');
But that didnt helped at all.
- how can i display multiple lines text caption in select tag?
i am using
<select>to make a list inside a select tag element with fixed width. let's say it is 200px.
this is my problem : my caption was cropped due the
<select>fix width.
and this is my expectation :
expectation
any suggestion to achieve that goal without editing the option caption?
- Angular 2 ngSubmit.emit() doesn't change the <myform>.form.submitted property
My following code triggers the
addResult()method property, but the property submitted is always empty. Any guesses?
<form class="form-horizontal" (ngSubmit)="addResult()" # <p>is form submitted? {{resultForm.form.submitted}}</p> ... <button type="submit" (click)="resultForm.ngSubmit.emit()" class="btn btn-primary" data-Sauvegarder</button> </form>
- multiple property does not work in select component
Hello M working on angular 2 app, I m using select to display multiple values and then want to select multiple values at a time, so i tried with 'multiple' but it does not work.
<md-select <md-option * {{food.viewValue}} </md-option>
m working on angular 2.4v
- ng serve throws node_modules appears empty error
I just started learning Angular 4, and as part of learning process i did the following:
Install
Node.js (version 8).
Ran this command
npm install -g @angular/cli
created a new project through CLI:
ng new my-first-app
As soon as i ran this command: ng serve, i got an error
node_moduleappear empty, you may need to run 'npm install'. Once i run npm install, it installed a few libraries and now
ng servebuilds and runs the project. i am trying to understand why did i need to
npm installand what did it install? shouldn't all the prerequisites have been installed with this command
npm install -g @angular/cli
- How is a merge conflict valid in a React, Typescript project
I found the code, pasted, below checked in to our React/Typescript - JSX/TSX project. It contains a Git merge conflict that hasn't been resolved.
The code builds (through Fuse-box) and runs in the browser!
The "transpiled" code results in the top element being resolved as the root element of our component and the second element (beginning ".app-container") being ignored.
It appears, that in some situations git merge conflicts can be resolved though Tax/JSX interpretation / parsing / transpilation.
My questions are: How does this work? Is this behaviour intentional?
export const App: SFC = () => ( <<<<<<< HEAD <Provider store={window.uglySolution}> <Router history={customHistory}> <Switch> <Route exact <Provider store={window.uglySolution}> <Router history={customHistory}> <Switch> <Route exact path='/' component={Welcome}/> <Route exact path='/advice' component={PageLayout}/> <Route exact path='/login' component={Login}/> <Route exact path='/manage' component={ManageLayout}/> </Switch> </Router> </Provider> </div> >>>>>>> f81b0b1b458e3d41f91faa2e726be6d88a35d9f8 );
-..
- Typescript consistently gives a positive value even when result is negative?
Maybe I am being extremely stupid but for the life of me I can not understand why I am always getting a positive value from this piece of code.
let totalInput = 0; let totalOutput = 0; day.totalCost = 0; for (let i = 0; i < this.events.length; i++) { if (day.date.getDate() === this.events[i].start.getDate()) { if (this.events[i].color === colors.green) { totalInput = totalInput + this.events[i].amount; } else if (this.events[i].color === colors.red) { totalOutput = totalOutput - this.events[i].amount; } } this.dayTotal = (totalInput - totalOutput); day.totalCost = this.dayTotal; }
Even when I log out my values and the calculation it shows that everything is accurate however for whatever reason, after I assign my calculation to a value it always leaves the variable positive when it should be negative based on my values inputted.
All help would be greatly appreciated as I can't understand why this is for the life of me!
- Can't use promise inside class functions in typescript?
Using the class option I planned to create a class with functions for CRUD operations in typescript. (like CreateStudent(),updateStudent(),listStudents(),ViewStudent()) So first I created a listStudent function
class student { listStudent (apiUrl:string) { this.usePromise(apiUrl).then(function(){ console.log("api call completed"); }); } usePromise<T>(apiUrl:string):Promise<T> { let p: Promise<T>; p = new Promise(() => { var request = new XMLHttpRequest(); request.onreadystatechange = function() { ... } ... }); return p; } } let s:student = new student(); s.listStudent("api/list.php");
Here initially I tried like this
usePromise(apiUrl:string):Promise {}
I got an error saying
generic type 'Promise' requires 1 arguement
So I read about generic types and then I implemented it in the usePromise function. Now I am getting an error on promise object creation
new Promise()saying
Promise only refers to a type but is being used as a variable here
- Why this error, I declared promise correctly as the return type creating object of that type?
- Instead of this, wherever I try to create a promise object inside any class function I get the same Error?
- Value of "THIS" in handler functions in React
export default class DetailsPage extends React.PureComponent { constructor() { super(); this.state = { data: '', isModalOpen: false, }; **//this.openModal = this.openModal.bind(this);** } openModal() { console.log(this, "this in Handler"); this.setState({ isModalOpen: true }); } closeModal() { this.setState({ isModalOpen: false }); } render() { console.log("this in render detail page ", this ); return ( (<div className="left"> <button className="btn btn btn-primary" type="button" ***onClick={this.openModal}***>Edit</button> </div> ); }
}
When I bind my handler function to context of class "THIS" in handler function becomes THIS of my class. But if i don't bind it then "THIS" in handler function comes out to be null. my doubt is why does it come out to be null in later case.
- Asynchronous code, how does it work? Promises and callbacks
I have tryed to find answer on web, and did it partly. But I still can not completely understand how JS can run ansyncronous code?
My seeing of things:
JS give us ability of asyncronous programming. That means that we can start first task, then while one is in progress we can start second task, etc. Before js can start second task it should be freed from the previous task. It can be achived with 2 ways:
- js by its own end the task (the code which should be processed by js only)
- js can start the task which should be processed by filesystem for example. In this case js, do its work, pass the task to filesystem and starts to process other queued tasks. When js is freed and filesystem have returned the result, js can continue that task.
So we can not achive asyncronous by just writing the next code:
function doSth( callback ) { let arr = []; for ( let i=1e6; i > 0; i-- ) arr.push( i ); callback(); } doSth( console.log.bind( null, 'I am callback' ); console.log( 'just a line' );
due to doSth() contains only js's work it will be completed first and then just appear 'just a line'? So it is not asyncronously, right? But if we will have filesystem task insted of loop, we will have asyncronous function?
And one more question: Are promises really asyncronous? How can they be asyncronous (i mean, can other tasks be processed at the time of promise processing), either promises just mimics asyncronous code? *I know, there is additional queue for promises.
Maby I just don't understand some base? I'll be glad if you can explain me to make my questions more explictly for me.