I have two places need to add a css class called myClass dynamically. I only want to add this class when $root.myBool is true. I got one of them work using this:
<ion-side-menu-content class="ng-class: $root.myBool ? 'myClass' : ''">
But I can't get the other one work. Here's the issue, this one above is written in cshtml directly. But the other one is added using angularJS inside javascript file. The other one looks like this in .js file var container = jqLite("<div class='class1 class2'>"); I want to add myClass right after class2, something like:
var container = jqLite("<div class='class1 class2 ng-class: $root.myBool ? 'myClass' : '''>");
I tried, but couldn't make it work. Hope someone can help..
Also I have a second idea to achieve this, since myClass is really only one line of style:
.myClass {
top: 78px;
}
So I was thinking maybe I also can change the top attribute inside javascript. So I'll add the class like this var container = jqLite("<div class='class1 class2 myClass'>");
Then change the top attribute inside the javascript where I change myBool:
$scope.myBool = false;
//get 'myClass' somehow and change the attribute 'top' here.
I know for jQuery I can do $('.myClass').css("top", "0px");. But I'm using ionic here, so the syntax is different, that's my issue.
So there're two ways I can think of to do this, make either one works will be more than enough for me. Thanks a lot!
If you generate HTML on the fly, you need to $compile it:
$compile(container)(scope);
SO question
Explanation and examples
Furthermore, I think writing ngClass as its own attribute in the form of ng-class="{'myClass': $root.myBool}" is much cleaner and less error-prone than the form inside a class attribute.
Tying it together:
var container = "<div class='class1 class2' ng-class=\"{'myClass': $root.myBool}\">";
element.append($compile(container)($scope);
There's not need to run it through jqLite before compiling it.
In my opinion you could use simply ngClass and ngStyle:
Controller:
$scope.topPx = '20px';
HTML:
<ion-side-menu-content ng-class="{'myClass': $root.myBool}" ng-style="{'top': topPx}">
Related
I currently have this (in jade)
div(ng-class = "{'{{cardselector.products[0].imageCarousel}}':
cardselector.products[0].imageCarousel != null}")
When the page loads and the imageCarousel object is updated and then I expect it to add the class evaluated to the div but that's not happening. It's only evaluating the class but not adding it to the div.
Could anyone help?
With my understanding of Pug, what you're doing is setting the class on your div to ng-class, what you want is to set the attribute ng-class to your value.
This could be accomplished by the following:
div(ng-class="{'{{cardselector.products[0].imageCarousel}}': cardselector.products[0].imageCarousel != null}")
To set the class to the value of the variable
div(ng-class="cardselector.products[0].imageCarousel")
I used Teh's plunkr to show what I mean.
https://codepen.io/anon/pen/xLEobm
Note: I'm still unsure of when you're compiling through angular, so it still might not render if your template is interpreted after angular compiles.
The following jade (pug) code seems to be working:
div(ng-app='')
div(ng-controller='MyCtrl')
div(ng-class='[cardselector.products[0].imageCarousel]') Hello!
Demo: https://codepen.io/anon/pen/gxwyKj
Can some one show how I can change the InnerHTML of the titles class to be the same as the alt attribute. For the actual website jarretonions.co.za
Thanks
$(document).ready(function() {
$(".pic").on("click", function() {
$(".modal").show();
var srclong = $(this).attr("src");
var srcshort = srclong.split("_");
var srcextension= srclong.split(".");
$(".modal img").attr("src", srcshort[0]+'.'+srcextension[1]);
************is it something like this********
var title = $(this).attr("alt");
$(".modal span").InnerHTML= title;
OR
document.getElementByClassName('titles').innerHTML = title;
})
+
echo
"<div class='art'>
<img class='pic' src='img/".$row["name"]."_tnail.jpg'
alt='".$row["name"]." • ".$row["year"]." • ".$row["type"]."'
height='auto' width='100%'/>
<div class='modal'>
<img class='big'/>
<span class='titles'></span>
</div>
</div>"
;
Since you're using JQuery, you can select those elements using $(".title") and change them directly. Something like so:
$(document).ready(function() {
$(".pic").on("click", function() {
$(".title").text( $(this).attr("alt") );
})});
Here's a fiddle: https://jsfiddle.net/wmjtfLja/1/
Note that if you have more than one element of class .title, they will all change. So you may want to select the title element by id or by relative path from the clicked image.
Realizing in advance, the danger of providing an answer that is not (superficially) fully aligned with the question, I was struck by the comment from melpomene, whom I initially thought was refering to things not existing in jquery.
melpomene is 100% correct, since getElementByClassName does not exist.
The correct syntax is getElementsByClassName.
Having said that, helloworld is also correct (syntax errors aside), since loading jquery for every little task is really redundent, and one can manipulate by class with little more half a dozen lines of pure javascript.
But, getting elements by class has dangers, since the return is a 'live' array.
For example, with dylan's original question, getting by class is only useful to return the first instance (the array length is just a guide of how many elemnts it applies to). Therefore, for dylan to make changes as he proposed, each requires its own button. (which also means, michael that I believe you are incorrect when you say it will affect all elements with same class name - oth, you are fully correct in noting that one should inpsect for other values (or change the class name) when running loops on the attribute).
Consider the following (on the fly class change);
function otf_cls_change(cls_original,cls_replace){
var a=document.getElementsByClassName(cls_original);
l=a.length;
if (l==0){return 0;}
do {
a[0].setAttribute('class',cls_replace);
a=document.getElementsByClassName(cls_original);
l=a.length;
} while (l>0);
}
This is effective for changing class names on the fly.
But, if we modify the code and
//change this a[0].setAttribute('class',cls_replace); // to
a[0].innerHTML='this_html';
It will cause the browser to hit an endless loop.
Why? because the live array returned by ElementByClass will only process the first item (even if you try to loop the array).
Therefore, while changing the class on the fly is fun and very do-able, I'd strongly suggest that using it to change any attrib that is not specific to the class id is a bad idea.
Changing the class attrib in conjunction with another attrib is fine.
For example,
a[0].innerHTML='this_html'; //do this first
a[0].setAttribute('class',cls_replace); //then this
The above will work to loop class defined elements.
On a point of massive personal hypocrisy, I do get annoyed when people ask for pure javascript solutions, and then some wing nut chimes in with jquery. I guess I'm doing the opposite here, since evidently, the question was jquery related, and here I am throwing out pure javascript. Sorry bout that.
btw, dylan, good luck with it. glad you bit back on the negative comment. Too many people here are terrified of offending, and wind up get bullied.
hth,
Gary
I am new to angularJs. there is a requirement need to assign css property to component at/from js file level. I have kept debugger, after assign css style to component. In debugger level I can able to see all applied css property to component behavior will be good. Once completes page load, I am not able to see applied css, from js file. From my side may be some overwriting/removing css style. How to achieve this one using angular/JavaScript/J query, great appreciate.
Here is my code.
By AngularJS
angular.element.find('.ctp-textfield')[0].style.width = "75px !important";
angular.element.find('.ctp-textfield')[0]["ng-style"] = "{height: 75px}";
By JavaScript
document.getElementById('Idname').style.width = "75px !important";
By JQuery
$('#idname')[0].style.width = "75px !important";
$('#idname').style.width = "75px !important";
The way to do DOM manipulation in Angular is to use a directive. All of the above snippets of code look like they are not running inside the link function of a directive so will not work as you expect (but theres not enough context to tell what you're doing).
see:
https://docs.angularjs.org/guide/directive
http://www.sitepoint.com/practical-guide-angularjs-directives/
http://www.ng-newsletter.com/posts/directives.html
http://www.befundoo.com/university/tutorials/angularjs-directives-tutorial/
https://github.com/angular/angular.js/wiki/Understanding-Directives
I have a search page that is used in multiple places with multiple 'themes' throughout my site. I have a few divs that can have their background color changed based on a radio button selection (whether they are enabled or not). I can do this just fine by changing the css class of the div on the fly with javascript.
However, these themes could potentially change, and the background color is grabbed from a database when the page is created. Right now I do this in the C# codebehind:
string bgStyle = "background-color:" +theme.searchTextHeaderColor +";";
OwnerSearchHeader.Attributes.Add("style", bgStyle);
In the Javascript I need to change this color to make it look disabled, and when the user clicks back to this div I need to re-enable it by changing it back to its original color. But since I only knew this color in the code-behind, I don't know what it was in the Javascript.
So my thought was to create a css class in the resulting HTML page when the page is loaded with the background color I need. Then I could simply switch from the divEnabled and divDisabled class in the javascript. But I'm not exactly sure how to do that.
Alternatively I could create a hidden element, assign it the 'enabled' style, and use that as a reference in the JavaScript when enabling my div. This seems like a hack but maybe its the easiest way. I'm still new to a lot of this, so I'd appreciate any suggestions. Thanks for the input!
So my thought was to create a css class in the resulting HTML page when the page is loaded with the background color I need. Then I could simply switch from the divEnabled and divDisabled class in the javascript. But I'm not exactly sure how to do that.
Yes, this is the anser; do this. In the <head> of your document add a <style> and put your CSS in there like so: (my Asp.NET is a little rusty so forgive me if it has some hicups ;) )
<style>
<!--
.divEnabled {
background-color:<%=theme.searchTextHeaderColor%>;
}
.divDisabled {
background-color:gray; /* or wtv */
}
-->
</style>
You could also put it in an external CSS file, which may be a good idea.
Then write some JavaScript to add/remove the class attribute (I'm going to ask that you don't call is the "CSS Class" ;) )
var ownersearchheader = document.getElementById("<%=OwnerSearchHeader.ClientId%>");
// changing the class attribute to `divDisabled`
var newClassAttribute = ownersearchheader.getAttribute("class").replace(/\bdivEnabled\b/, "divDisabled")
ownersearchheader.setAttribute("class", newClassAttribute);
// ... or,
// changing the class attribute to `divEnabled`
var newClassAttribute = ownersearchheader.getAttribute("class").replace(/\bdivDisabled\b/, "divEnabled")
ownersearchheader.setAttribute("class", newClassAttribute);
This is indeed a mouthfull, so, like #Haydar says, you might want to use jQuery, which offers easy-as-pie addClass(), removeClass() and toggleClass() methods.
You can use the jquery .toggleClass method.
Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
Here is the link to the api doc.
Jquery API
I have asp:Table with number of asp:Label inside asp:FormView, it represents short stats info.
I need to set Label.CssClass to "red" if it's text isn't "0".
Currently I do this on FormView.DataBound event. But think that it's better to use JavaScript and probably jQuery. How can I do that?
Sorry for dummy question - I'm new to jQuery. Thanks!
You can do this using jQuery (you can also give the Table or FormView a class, probably easier in aps.net instead of the ID like I have below):
$("#formViewOrTableID span").filter(function() {
return $(this).text() !== "0";
}).addClass("redClass");
If you give the labels a class you want affected, say set all the Labels you want included to CssClass="styleMe", you could change $("#formViewID span") to
$("#formViewID span.styleMe") to be more specific.