Is is bad practice to ID each (used) element in html? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am wondering what the best practice would be to manipulate certain elements in an html page using jquery. As it stands now, I have a panel, with an embedded form which includes an input box, checkbox, submit/reset/test buttons. Right now I have each of these elements assigned an id so I can take the appropriate actions as each element is changed/selected. However, I feel as if my code is becoming quite messy and unreadable by assigning and managing each element by id. I know that it is efficient for the browsers to select by id, but is it better to simply give the panel/form an ID, and then call different selectors inside of the panel/form? Are there any suggestions for selecting some of the elements I have assigned IDs below? (The ones I am modifying..etc). Thanks!
<div class="row">
<div class="col-lg-6">
<div class="panel panel-default" id="sample_panel">
<div class="panel-heading">
Heading
</div>
<div class="panel-body">
<form role="form" id="form1">
<div class="form-group">
<h4>Subheading</h4>
<div class="form-group input-group">
<span class="input-group-addon" id="input_addon">some_text</span>
<input type="text" id="input1" class="form-control" placeholder="Enter text">
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<span class="help-block">
<input type="checkbox" id="cb1" >some_text
</span>
</label>
</div>
</div>
<button type="submit" class="btn">Submit</button>
<button type="reset" class="btn id="reset_btn">Reset</button>
<button type="button" class="btn" id="test_btn">Test</button>
<i id="some_image"></i>
</form>
</div>
<div class="panel-footer" id="footer"></div>
</div>
</div>
<!-- /.col-lg-6 -->
</div>
<!-- /.row -->

Remember that IDs are unique identifiers, and for that reason should have more specific names. I would use them only when they are actually necessary, and when a class wouldn't be a better way to identify them.
Pile on the classes, but use IDs a bit more sparingly. I struggled with this as well when writing my first MVC app. Good luck!
Don't forget there is a code review site on StackOverflow as well.

I give id's to major elements in the page that contain subsets of the page, and also important and unique elements that I would want direct access to. I don't give an id to each and every list item, link or div because it clutters the code and it's a potential maintenance nightmare. You won't select most elements of the page, and you'll often access multiple elements at the same time - classes are vastly more useful for this.
So while you are correct that accessing elements by id is very quick and efficient, the selector system is powerful and useful because you can select elements in a variety of ways. Take advantage of those other selection methods too, you'll get a lot more done with jQuery.

Related

How can I select an Animatedmodal to display different demos using one ID

I have a website that i am trying to personalize and I am trying to use the AnimatedModal.js framework. I have been able to display some content in one modal, but when it comes to make several modal it gets tricky, because there is just one ID. My question i, how can i use the same ID and change the content for other modals(demo03,demo04..etc.), in order to personalize each.
I will put some code in order to understand the problem
I have been reading the documentation but I am still stuck in this problem.
<!-- single work -->
<div class="col-md-4 col-sm-6 ads graphics">
<a id="demo02" href="#animatedModal" class="portfolio_item">
<img src="img/portfolio/03.jpg" alt="image" class="img-responsive" />
<div class="portfolio_item_hover">
<div class="portfolio-border clearfix">
<div class="item_info">
<span>Should open here </span> <em> ads / Graphics </em>
</div>
</div>
</div>
</a>
</div>
<!-- end single work -->
Then I have the demo where it displays the content of the modal, where it has the #animatedmodal ID
<div id="animatedModal" class="popup-modal ">
<!--THIS IS IMPORTANT! to close the modal, the class name has to match the name given on the ID -->
<div id="btn-close-modal" class="close-animatedModal close-popup-modal">
<i class="ion-close-round"></i>
</div>
<div class="clearfix"></div>
<div class="modal-content ">
<div class="container">
<div class="portfolio-padding" >
Hello World
</a>
</div>
</div>
</div>
</div>
this is my Js file where there is just one element assigned to it, to avoid showing the same content into all different classes.
$("#demo02").animatedModal();
I don't think it can be done without hacking the plugin.
As a matter of fact, the script jQuery.animatedModal ALWAYS TARGETS the page element which has id="animatedModal"
You can see the plugin source code here:
https://cdn.jsdelivr.net/npm/animatedmodal#1.0.0/animatedModal.js
...
//Defaults
var settings = $.extend({
modalTarget:'animatedModal',
...
Here is the AnimatedModal reference:
https://joaopereirawd.github.io/animatedModal.js/
At the bottom of the page, I can't see any OPTION regarding how to specify a different target, all options are about styles and animation features.
At this point, I think the only way to allow multiple modals on the same page is to rewrite the plugin, but I'm pretty sure you don't want to choose this way.

Removing the whole div with JavaScript [duplicate]

This question already has answers here:
Remove element by id
(19 answers)
Remove parent div by class name - jquery
(5 answers)
Closed 6 years ago.
Before you mark this as a duplicate, this is how my question is different.
Due to the lack of content actually on google, all that I can find is
removing the parent ID, I don't think that applies as the parent ID
would only remove panel-body, then leave panel-heading and the panel
div there.
I wanted to ask a quick question that I couldn't find any help with online. I have a bootstrap panel, which has two div's insdie of it, one for the panel-header and one for the panel-body. Inside the panel-body div I have a btn btn-success button that I want to remove the whole panel on click.
<div id="draggable" class="habbo-notification panel panel-default">
<div class="panel-heading">
Panel Header
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-4">
<font color="#B00049">
<h1 style="font-size:144px;margin-top:0;margin-left:14px;"><i class="fa fa-globe fa-6" aria-hidden="true"></i><h1>
</font>
</div>
<div class="col-md-8">
<p>
Some content here
</p>
<br>
<div class="btn btn-success" onclick="" style="width:100%">Close this</div>
</div>
</div>
</div>
</div>
</div>
In javascript or jquery (don't mind which one), how could I remove the entire div onclick of the button, without knowing the ID or class, or having any access to the panel div at all. I declare the panel-body's content somewhere other than the place where I declare the panel and it's two divs panel-body and panel-header.
I want to remove the whole panel div that the button is assigned to, on click?
<div class="btn btn-success" onclick="" style="width:100%">Close this</div>
Can anyone help?
The jQuery method is this one-liner.
$('.btn-success').on('click', function(){
$(this).closest('div.panel').remove();
});
The .closest() function looks for the nearest parent matching the supplied selector. In this case, it checks each parent of this until it sees div.panel.
You could drop this in your onclick="", though onevent attributes are deprecated in HTML. Standards expect events to be set within the Javascript.
I don't really get why you can't use the class(es) of the panel div like .panel, for example:
$(".btn").click(function(){
$(".panel").css("display","none");
});
But I think this would technically also work:
$(".btn").click(function(){
$(this).parent().parent().css("display","none");
});

Dynamically adding HTML form elements with Meteor

I'm very new to Meteor, enjoying it and am making some test apps to build my skills.
I want to add a form that allows dynamic addition of a phone number field. The idea being that I'm adding a company into the collection/database and one company may have 0 phone numbers, another might have 3 and another might have 20. So I want to be able to press say, a PLUS button or similar and have the input fields appear in the HTML.
I've played around with sessions a little and think they may be the key to the puzzle.
I have the following so far (for this part of the app):
My HTML template:
<template name="organisationAddForm">
<h3>Add a new organisation</h3>
<form name="addForm">
<div class="row">
<div class="col-sm-4 col-lg-1">
<p>Name</p>
</div>
<div class="col-sm-4 col-lg-1">
<input type="input" name="newOrgName" placeholder="Organisation Name">
</div>
</div>
{{> addPhoneNumber}}
<div class = "row">
<div class="col-sm-4 col-lg-1">
<input type="submit" value="Add Organisation">
</div>
</div>
</form>
</template>
and
<template name="addPhoneNumber">
<h4>Phone Numbers</h4>
<ul>
{{#each phoneNumber}}
<li>Number: {{number}} </li>
{{/each}}
</ul>
[ Add Phone Number ]
</template>
So far my Javascript is incomplete as I'm a bit stuck:
Template.addPhoneNumber.events({
// when user clicks the Add Phone link
'click .add-phone': function(event){
event.preventDefault();
}
});
The idea with the above is:
1- User clicks the add-phone link which will add a value to the session.
2- The each loop will be looping through the session data and re-drawing the form with however many inputs the session data tells it to draw.
I hope that makes sense and it's focused enough.
I'm not asking for anyone to write code for me, more help me with direction (is this the right direction?) and suggestions on how to go about it. I want to learn programming and be better at this and am happy to do the hard yards. This has just got me stuck, so here I am. :-)
Any advice greatly appreciated.
Rob

Update visual styling of dynamically added checkbox in jQuery Mobile

I'm currently adding a bunch of checkboxes dynamically during the "pageinit" event, which I am able to both add and check successfully. The checkboxes are added by appending instances of the following stub to a "ul"-component:
<li>
<div class = "new-student">
<img class="profile-img nav-ui-thumbnail ui-mini" src="../images/prof_img.gif">
<!-- Block A -->
<div id="grid" class="ui-grid-a ui-mini">
<div class="ui-block-a ui-mini">
<div class="ui-bar ui-bar-a ui-mini">
<h2 class="name-student">Name</h2>
<p class="attendingtime-student">00:00</p>
</div>
</div>
<!-- Block B -->
<div class="ui-block-b">
<div class="ui-bar ui-bar-a ui-mini">
<h2 class="pickuptype-student">null</h2>
<p class="pickuptime-student">00:00</p>
</div>
</div>
</div>
<form>
<!-- Attending -->
<fieldset class="fieldset ui-overlay-shadow" data-role="controlgroup" data-type="horizontal" class="localnav">
<input class="attendance0-student" name="checkbox-h-2a" id="checkbox-h-2a" type="checkbox">
<label for="checkbox-h-2a">1</label>
<input class="attendance1-student" name="checkbox-h-2b" id="checkbox-h-2b" type="checkbox">
<label for="checkbox-h-2b">2</label>
<input class="attendance2-student" name="checkbox-h-2c" id="checkbox-h-2c" type="checkbox">
<label for="checkbox-h-2c">3</label>
</fieldset>
</form>
</div>
However; I am unable to update the visual styling of the checkboxes, which result in all checked boxes looking like this:
I've tried calling ".checkboxradio.('refresh')" but it only results in an error (saying I can't call that method on a component that has yet to be initialized).
Please help!
Regarding this:
I've tried calling ".checkboxradio.('refresh')" but it only results in
an error (saying I can't call that method on a component that has yet
to be initialized).
Usually when this kind of error occurs you need to do this:
$('#someId').checkboxradio.().checkboxradio.('refresh');
First call will initialize checkboxradio widget and second one will enhance its markup.
But this is not case with checkbox widget, to enhance dynamically added checkbox you need to do this:
$('[type="checkbox"]').checkboxradio();
Without refresh parameter.
And here's a working example: http://jsfiddle.net/Gajotres/VAG6F/77/
There are of course other solutions, read this article if you are using older versions of jQuery Mobile up to 1.4 (mentioned functions are currently deprecated).
If you are using jQuery Mobile 1.4 and you are planing in using future versions then use this method:
$('.ui-content').enhanceWithin();
Read more about it here.
There's a third option, instead of pageinit use pagecreate event. Like pageinit it will trigger only once but unlike pageinit it triggers before jQuery Mobile enhances active page. So everything appended at this point will automatically become enhanced.

Changing section focus on button click in Foundation CSS

I am using Foundation CSS and need some help on the sections object. I have a tabbed section on my page
<div class="section-container tabs" data-section="tabs">
<section id="section1">
<p class="title" data-section-title>Step 1</p>
<div class="content" data-section-content>
<input type="text" id="firstname" placeholder="First Name">
</div>
</section>
<section id="section2">
<div class="content" data-section-content>
<input type="text" id="phone" placeholder="Phone">
</div>
</section>
What I am trying to do is have a next button on section1 that would take me to section 2 by using this
<button class="small button" id="next1" onclick="document.getElementById('section2').className ='active';document.getElementById('section1').style ='padding-top: 49px';document.getElementById('section1').className ='';document.getElementById('section1').style ='';"> Next </button>
This however is not working. What happens is that by clicking the button it takes me to section 2 for a brief section and then brings me back to section 1. Any help on how I can nail this.
Few things are missing and others not understood.
You need to give the focus. with focus(); so it takes you there.
You cannot change className if your element has no class attribute. You need to create it first or leave it empty in html.
To change style via javascript, you need to call the rule and then give it a value. element.style.paddingTop='49px';
To set focus on something else than form element or links, you may add the attribute tabindex="0" to the element your want to catch focus state.
a few change to your code , so you can experiment some of the things i say. http://codepen.io/gcyrillus/pen/pCikI
I wish you success in learning :)

Categories