How Can I Rewrite This More Efficiently - javascript

I have to believe that there's a better way to write the below code. Thanks in advance.
var hProtein = $('#protein-lbl');
var hCarb = $('#carb-lbl');
var hFat = $('#fat-lbl');
var hTotal = $('#totalCalories');
// Normal Calc vars
var nProtein = $('#protein-normal-lbl');
var nCarb = $('#carb-normal-lbl');
var nFat = $('#fat-normal-lbl');
var nTotal = $('#totalCalories-normal');
// Hide calculations until bodyweight is entered
hProtein.hide();
hCarb.hide();
hFat.hide();
hTotal.hide();
nProtein.hide();
nCarb.hide();
nFat.hide();
nTotal.hide();

Perhaps giving the HTML elements a class will work?
var $ele = $('.class-name');
$ele.hide();

The best solution is to have the default condition of the page specified in HTML/CSS, so it displays properly at first and you don't have to run a bunch of javascript just to set up the default condition.
So, if what you're trying to do is establish the default condition upon page load, change the display style of all these elements to style="display: none;" right in the HTML so they start out with the right state.
Or better yet, give them all a common class name and create a CSS style rule so they are all initially hidden. Doing this in the markup/CSS will prevent them showing and then hiding as your script runs - they will just start out with the right state.
CSS:
.initialHidden {
display: none;
}
HTML:
<div id="totalCalories-normal" class="initialHidden"></div>

add common class to element the hide it by this way
$('.common-class-name').hide()
OR
Put all elements in Single div wrap and hide it by that id

I would do this :
$([
'#protein-lbl',
'#carb-lbl',
'#fat-lbl',
'#totalCalories',
'#protein-normal-lbl',
'#carb-normal-lbl',
'#fat-normal-lbl',
'#totalCalories-normal'
].join()).hide();

Why not wrap the labels in a fieldset and hide the fieldset

Related

script that applies a style to newly created elements

I am writing a tampermonkey script that changes the style of an element whose class starts with "blocked". So i have this code:
var blockedelements = document.querySelectorAll("[class^=blocked]");
var element = blockedelements[0];
element.style.display="none";
for simplicity this is only for the first element but i know how to iterate through each one and this code as it is works. the webapp dynamically creates new elements with this class and i want the script to execute for each newly created element which is what i don't know how to do. I want a pure JS solution, not jquery. Is this what a listener is for? i don't know much about javascript.
I would appreciate any pointers, thanks
Instead of manually changing the display value for every instance of the element, you could use JavaScript to add a page-wide style rule to hide all of them. That way you can let the browser handle applying the rule to both existing and future instances of the element for you.
Rough idea:
var rule = "[class^=blocked] { display: none }";
var styleElement = document.createElement("style");
styleElement.type = "text/css";
if (styleElement.style.cssText) {
styleElement.style.cssText = rule;
} else {
styleElement.appendChild(document.createTextNode(rule));
}
document.getElementsByTagName("head")[0].appendChild(styleElement);

The margins in div of new tab not at all taking effect

Hi I am creating dynamic form in new tab using JavaScript. Margin effects on div are not taking effect. I am neither able to set the margins using class and id in css nor using div.setAttribute. Below is the code.
`
var openWindow = window.open('dynForm.html','_blank','');
var windoc=openWindow.document;
windoc.write("This is dynamic form ");
var div=document.createElement("div");
div.setAttribute("style","border:solid");
div.setAttribute("style","margin-left:1cm");
div.setAttribute("style","margin-right:1cm");
div.setAttribute("style","margin-bottom:1cm");
div.setAttribute("style","margin-top:1cm");
div.setAttribute("style","background-color:lightblue");
`Only background color is taking effect on the new tab. The below screen shot shows how the screen looks irrespective of the values of margin.
Quesstion 2: No class or id attribute in my css is being applied to div.
#myDIV2{
background-color:lightblue;
}
I tried div.id="myDIV2";
I also tried div.setAttribute("id","myDIV2");` I applied the same using class also, but still couldn't find any difference. I do not know why its not working and what went wrong here. Please help
You're overriding the styles every time you call setAttribute, try combining the styles and then set the style attribute only once:
var openWindow = window.open('dynForm.html','_blank','');
var styles= [
"border:solid;",
"margin: 1cm;",
"background-color:lightblue;"
];
var windoc=openWindow.document;
windoc.write("This is dynamic form ");
var end_styles = "";
for (var i=0; i<styles.length;i++) {
end_styles += styles[i];
}
var div=document.createElement("div");
div.setAttribute("style", end_styles);
Note: the fiddle won't work on stackoverflow, I used it because it's easier to format code
This is happening because your all style attribute are getting overridden by previous div.setAttribute and your last attribute div.setAttribute("style","background-color:lightblue"); getting applied. Try to put all styles in one go. div.setAttribute("style","style1:value1;style2:value2;style3:value3;");

change name of DIV width JavaScript

I am using following code:
...
<div id="divcontainer1">
...
<div id="divcontainer2">
...
</div>
</div>
...
Now, I want change "divcontainer2" at a later point of time in the Div "divcontainer3".
What is the right way to check is exist divcontainer2 and when true,
change in divcontainer2 width javascript ?
Thank you,
Hardy
It is probably not nest practice but you can do this by changing the .outterHTML of the element. You would likely want to improve on this but here is a quick example. The last line checks if div 2 exists.
var div2 = document.getElementById("div2");
var html = div2.outerHTML;
var idx = html.indexOf(">");
var newtag = html.substring(0, idx).replace("div2", "div3");
div2.outerHTML = newtag + html.substring(idx, html.length - 1);
var contents = document.getElementById("div3").innerHTML;
alert(document.getElementById("div2") != undefined);
All you do is
get the element .outterHTML
get the substring representing the tag.
Replace the text that defines it
Set the .outterHTML tag to our new string
Now you have a newly named div that keeps all of its attributes, position in the parent and content.
The alert line is how you check for the existence of an object.
I don't believe that there is a "proper" way to do this, however I would store the contents of divcontainer2 in a variable, and then do something like this
var containerOfDivContainer2 = document.getElementById("containerofdiv2");
containerOfDivContaier2.innerHTML = "<div id='divcontainer3'>"/* insert div contents */+"</div>";
Of course, this requires you to put divcontainer2 in a div called containerofdiv2 but it works.
If using jQuery, this will do it:
$('#divcontainer2').attr('id','divcontainer3');
But you shouldn't be changing IDs. Use classes instead and then use the jQuery's toggleClass() function, like:
<div id="divcontainer1">
...
<div id="divcontainer2" class="style1">
...
</div>
$('#divcontainer2').toggleClass("style1 style2");

How to entirely disable/enable html elements?

I have several elements on the page. Something like:
<div id="el1"><div id="el2"><span id="el3">1</span><span id="el4">2</span></div><span id="el5">3</span></div>
I need to disable/enable any of them, using their ids.
<input type="radio" name="do" onclick="disable(document.getElementById('el4'));">
<input type="radio" name="do" onclick="enable(document.getElementById('el4'));">
What should be in disable() and enable() functions to really disable elements?
By "disable" I mean make it invisible for user, inaccessible by "id" and be restorable by "enable()" function.
Is it possible to turn elements on/off? Entirely, I mean.
function addEl4(){
var elem = document.getElementById('el2');
var newElem = document.createElement('div');
newElem.setAttribute('id', 'el4');
newElem.innerHTML = 2;
elem.appendChild(newElem);
};
function disable(elem){
var container = document.getElementById('el2');
container.removeChild(elem);
};
If you are talking in terms of removing the element from the page completely.
Then you can use the .removeChild() method..
Then need to append it to the div you are talking about..
Check Fiddle
You may use
document.getElementById('el4').style.display='none'; // hide
document.getElementById('el4').style.display=''; // show
You could define functions like this :
function hide(element){
element.style.display='none';
}
function show(element){
element.style.display='';
}
I really suggest not to use the enable and disable words, as they have other meanings (a disabled widget is one you can see but you can't change).
A better solution would be to define a css class
.hidden {
display: none;
}
and change the class in js :
document.getElementById('el4').classname='hidden'; // hide
If you want to completely remove an element, you may use removeChild :
var node = document.getElementById('el4');
node.parentNode.removeChild(node);
but it's almost never useful. Prefer to hide as is commonly done.

How to create an effect higher up in the view than the logic that determines it?

I have a simple if statement in my view that returns x = 0 or 1. Based on this simple result, I want to change the styling of the div that contains the entire section.
<div>
conditional that returns x=1 vs x=0 (and a few displayed items)
based on this loop, restyle the div
</div>
Let's say, if x = 1, I want to make background-color:rgb(210,215,220);
How can I accomplish this? I am not experienced with Javascript but I'm sure any code required would be very simple. Thank you!
Add an ID to your DIV like:
<div ID="colorThis">
conditional that returns x=1 vs x=0 (and a few displayed items)
based on this loop, restyle the div
</div>
Then do this:
if(x==1)
{
​document.getElement​ById('colorThis').style.background = 'rgb(210,215,220)'​​​​;​​​​​​​​​​​​​​
}
<script>
if(x==1)
{
$("#divid").css("background-color","rgb(210,215,220)");
}
</script>
Include jQuery, and give the div's id to divid

Categories

Resources