Hiding elements with a specified id - javascript

I have two different divs
var promptContent = $('<div id="errorr">').addClass("formErrorContent").html(promptText).appendTo(prompt);
var arrow = $('<div id="errorrarrow">').addClass("formErrorArrow");
I want to use their id in javascript like this
function windowclose()
{
document.getElementById('add_project').style.display="none";
document.getElementById('blanket').style.display="none";
document.getElementById('errorr').style.display="none";
document.getElementById('errorrarrow').style.display="none";
// $("#blanket").fadeIn("none");
// $("#add_project").fadeIn("none");
}
But here it hides only the 1st div. I want to hide all the divs with the same id. How can I do this?

Choose between to use name or id:
getElementsByName('errorr') searches in the DOM an element named errorr
getElementById('errorr') searches in the DOM an element with the id equals to errorr;
Try to change your code:
document.getElementsByName('errorr').style.display="none";
document.getElementsByName('errorrarrow').style.display="none";
to
document.getElementById('errorr').style.display="none";
document.getElementsById('errorrarrow').style.display="none";
also note that a DOM must have all unique IDs (as rule)
UPDATE:
Well, if you need to hide a set of divs I usually add at all of them a class like .element-to-hide:
<div id="asd" class="element-to-hide">...
<div id="lol" class="element-to-hide">...
<div id="foo" class="element-to-hide">...
Ant after just a touch of jQuery:
$('.element-to-hide').each(function(){
$(this).hide();
});
Hope this help

Even though using the same ID on many elements is semantically invalid, you could do it in a single jQuery line.
$('#errorr, #errorrarrow').hide();

Related

Function for adding and removing style on click and unfocus

I am trying to implement a function which changes style of element on click and remove it when unfocus. For ex: When element2 is clicked, it should remove class of other elements, and add class to the clicked element only.
<div class="dope" id="element777"></div>
<div class="dope" id="element2"></div>
<div class="dope" id="element11"></div>
<div class="dope" id="element245"></div>
<div class="dope" id="element60"></div>
.....(More are created automatically, numbers are not estimatable)
I couldnt know the element ids that are created. The only remains same is class.
I have tried this, but its an unprofessional approach.
$('#element1').click(function(){
$("#element1").addClass(dope2);
$("#element2").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
});
$("#element1").blur(function(){
$("#element1").removeClass(dope);
});
$('#element2').click(function(){
$("#element2").addClass(dope2);
$("#element1").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
});
$("#element2").blur(function(){
$("#element2").removeClass(dope);
});
What is the best approach for automating this function, instead of adding click and blur (unfocus) function to ALL of elements ?
You can listen for click events on any div with an id containing the word "element', then target its siblings elements (those that are not clicked, without referring to them by id). This might do it:
$("div[id*='element']").click(function(){
$(this).addClass('dope').siblings('.dope').removeClass('dope');
});
Your jQuery could be vastly simpler if you leverage this and siblings:
Instead of:
$("#element1").addClass(dope2);
$("#element2").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
It could be:
$('.dope').click(
function() {
$(this).addClass(dope2).siblings().removeClass(dope);
}
);
NOTE:
Do you have a variable called dope with the class name, or is dope the class name? If it's the classname, you need to put it in quotes: $(this).addClass('dope2'), etc.
If you are removing the class dope, then will want to add a class you can always use to select these elements (so that when you remove dope, it continues to work).
Button part:
$("div").click(function(){
if($(this).hasClass("dope") || $(this).hasClass("dope2")){
$(this).addClass("dope2");
$(".dope").not($(this)).removeClass("dope");
}
})
Blur part:
$("div").blur(function(){
if($(this).hasClass("dope") || $(this).hasClass("dope2")){
$(this).removeClass("dope");
}
}
I would recommend using the :focus css selector rather than using javascript to do what you are doing... Read more here. Instead of having a click listener, the focus selector will take care of that for you and automatically remove the styling when the element is out of focus.

Iterating through a list of elements and removing the cursor style on them based on inner text

I have a list of divs in the following structure, where the text in the a.status-progress will either say "in progress" or "not started":
<div class="plan-section">
<div class="tableView-row">
<p class="plan-name">
<a>some name</a>
</p>
<a class="status-progress">in progress</a>
</div>
</div>
<!-- same structure as above but not expanded -->
<div class="plan-section"></div>
<div class="plan-section"></div>
All the <a> tags with in each <div> act as links. What I would like to do is loop through each div, check and see if the a.progress has the string "in progress" with in it . If it doesn't I want to remove the cursor:pointer css property and any events attached to the <a> tags. Current my jQuery implementation is:
// remove linking if plan is not joined
$('.status-progress').each(function(i){
var planLinks = $('.status-progress, .plan-name a');
var planStatus = $(this).text();
if (planStatus === "in progress"){
planLinks.css('cursor','pointer')
}
});
This is not working properly though because I believe my logic with the each() is wrong or that I need to add another one later in the code block. Thanks for the help!
EDIT: Added proper class for status-progress
The line:
var planLinks = $('.status-progress, .plan-name a');
...will select all such anchor elements, not just the ones related to the current iteration of the .each() loop. One way to get just the related ones is:
var planLinks = $(this).closest("div").find("a");
That is, use DOM traversal methods to find the containing div and then select the anchors within it. Or you could go based on siblings, etc., but that is more fragile since a change to the html structure is then more likely to require a change to the JS.
But you don't really need the .each() loop if you do something like this instead:
$("a.status-progress:contains('in progress')") // find the 'in progress' anchors
.closest("div") // get their containing divs
.find("a") // find the anchors in those divs
.off() // remove the event handlers
.css('cursor','pointer'); // set the CSS property

Accessing elements inside dynamically created divs with HTML/Javascript

I'm quite new to javascript and JQuery programming. Usually, to access elements I give them an id, so I can get them like $("#"+id).blabla().
But now I need to dynamically create a div, and access elements inside it.
Something like
<div id="automaticallyGeneratedId">
<div ???></div> <!-- first div -->
<div ???></div> <!-- second div -->
</div>
What are the best practices to access and identify each of the inner divs?
I generate another id for them?
Or what?
I don't have the theory of selectors fully clear.
edit: modified the question from identifying a single inner div to identifying divs amongs many of them
You can maintain a pattern when you're generating id. For example:
if you always generate id like: myid1, myid2,myid3...
<div id="myid1">
<div></div>
</div>
<div id="myid2">
<div></div>
</div>
......
then you can try:
$('div[id^=myid]').find('div').foo();
OR
$('div[id^=myid] div').foo();
Here, ^= is start with selector, so div[id^=myid] will select div whose id start with myid.
You can also use Contain word selector which is ~= and use like $('div[id~=myid]'). This will select div with id contains word myid.
Instead of id if you want to use other attribute eg. name then change selector like:
$('div[name^=myid]') or $('div[name~=myid]').
It's usually a good practice that if you already have a reference to that outer div to just search from there using find.
You can give it an id, or if you want to use a more general approach you can use classes.
<div class="subdiv">...
$('#automaticallyGeneratedId').find('div.subdiv')
Usually, when you create them, you can assign event handlers and the likes straight on them. Like this:
var div = $( '<div></div>' );
div.on( 'click', function() {
// Do something when the generated div is clicked
});
// Then, add it to the DOM
$( 'body' ).append( div );
You don't need to bother selecting them with ID or classes, they're already available in your code.
Another way is to use event bubbling to handle newly created elements of the same class. A good link about this is this one: http://beneverard.co.uk/blog/understanding-event-delegation/
Many ways you can create an element and give him an Id or Class, or use the DOM to access it..
$("html").prepend('<div id="foo"></div>');
$("#foo").doSomething();
another way
$("#automaticallyGeneratedId").find("div").doSomething();
To access the div in the element with the id:
$("#automaticallyGeneratedId div").whatever
If you cache the divs you could use something like:
var myDiv1Child = $('div', myDiv1);
Create a delegated listener and within the listener you can find the element by doing this
//If a div inside the parent is clicked then execute the function within
$('.PARENT_CLASS').click("div", function(){
//This variable holds all the elements within the div
var rows = document.querySelector('.PARENT_CLASS').getElementsByTagName('div');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
console.log(this); //The element you wish to manipulate
}
}
});

jQuery click function using same classes

I have a dropdown function that I need to work only on the div clicked, not all (I have 14+ of the same classes on the page that need to be displayed when a certain one is clicked)
At the moment my jQuery is as follows.
$('.qacollapsed').hide();
$('.qa').click(function () {
$('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Of course, that is toggling all qacollapsed classes when there is 14 on the page (Q&A)
Is there a way for it to only drop down the one that is clicked?
the HTML
<div class="qa">
<h4 class="question"> </h4>
</div>
<div class="qacollapsed">
<p> </p>
</div>
It would be helpful to provide a snippet of HTML here, but I'll take a guess at the structure of your markup for now..
Instead of referencing all .qacollapsed elements, you need find elements that are close to the .qa that was clicked, e.g.:
$('.qa').click(function () {
$(this) // start with the clicked element
.find('.qacollapsed') // find child .qacollapsed elements only
.slideToggle();
$(this).toggleClass('active');
});
This will work if .qacollapsed is inside .qa - if not, you might need to use next (for siblings), or one of the other jQuery tree traversal methods.
Yo could find() it or use this as a context in the selector to choose only a descendent of the clicked object
$('.qa').click(function () {
$('.qacollapsed', this).slideToggle();
//You could do $(this).find('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Check out the jQuery selectors and why not just use $(this)?
$('.qacollapsed').hide();
$('.qa').click(function () {
$(this).toggleClass('active').next().slideToggle();
});
Personally, I'd give all the divs IDs, the clickable bit being the ID of the question in the database for example, and the answer just being id='ID_answer' or something, then use jquery to slide in the div with the id corresponding to the link clicked, ie
Var showIt = $(this).attr('id') + '_answer'
$('.qacollapsed').not('#'+showIt).hide();
$('#'+showIt).slideToggle;
That will hide all the divs without that ID and show the required one.
Dexter's use of .next above looks simpler though, I've not tried that as being relatively new to jquery too.

jquery toggling a div - how to do this with multiple ids?

I am new to Jquery. My setup is as follows:
I have a series of divs that need to be able to be toggled (display hidden and shown). Each div has an action that can be performed so a unique ID will be necessary to know from which div the event came from.
To toggle the div I have a button for each div (which is not located within the div to be toggled).
Right now without jquery, I use the button's onclick event to pass the ID of the corresponding div to be toggled. Using the unique ID I can do the following:
function toggleFlag(divId) {
var div = document.getElementById(divId);
div.style.display = (div.style.display=="block" ? "none" : "block");
}
divId is unique so I also know where the event comes from if action within the div is performed.
the anchor code looks something like this:
onclick="toggleFlag('id-111');"
where the '111' is the unique id
First off, is it even worth it to use jquery for this if the extent of my javascsript isn't much more complicated (aside from maybe simple ajax).
More importantly, how would this properly be done using jquery?
Update: I am very close to solving this. I managed to get it to work using one of the suggestions below requiring unique class names for each button. A couple of the methods suggest implementations where the class name is the same for all buttons (I want this in order to be able to statically assign styles to the button class), but I could not get these to work. Could somebody please elaborate on the solution? Thanks!
Let's say that you build your anchors to have an id that corresponds with the id of the DIV to toggle and further that they all have a common CSS class. For example,
Toggle
<div id="d_111">Some stuff.</div>
Now you could use jQuery to build the click handlers for all of these pretty easily.
$(function() {
$('a.toggleButton').click( function() {
var divId = $(this).attr('id').replace(/a_/,'d_');
$(divId).toggle();
});
});
You could do something like this:
HTML:
<button id="btnId1" class="divId1" value="Click me to toggle divId1"/>
<button id="btnId2" class="divId2" value="Click me to toggle divId2"/>
etc...
<div id="divId1">div 1</div>
<div id="divId2">div 2</div>
etc...
SCRIPT:
$(function() {
$("button").click(function() {
var divId = $(this).attr("class");
$("#" + divId).toggle();
});
});
This approach has the advantage of only defining the event once for all buttons. You could also use another strategy for storing the div id in the button information, like a non-standard attribute - which jquery can pick up as well, or make the div id a part of the button id like so:
<button id="btn_divId1" value="Click me to toggle divId1"/>
<div id="divId1">div 1</div>
and then extract the id of the div from the id of the button clicked (personally this is the approach I'd take)
Hope this helps
EDIT: To answer the first question, yes you would benefit from doing this with jQuery since it would shorten the amount of code that you are writing and it would allow you to move to unobtrusively assigning events to the buttons which is a good thing :)
EDIT 2: Using non-standard attributes:
HTML:
<button id="btnId1" divid="divId1" class="btnToggle" value="Click me to toggle divId1"/>
<button id="btnId2" divid="divId2" class="btnToggle" value="Click me to toggle divId2"/>
etc...
<div id="divId1">div 1</div>
<div id="divId2">div 2</div>
etc...
SCRIPT:
$(function() {
$("button").click(function() {
var divId = $(this).attr("divid");
$("#" + divId).toggle();
});
});

Categories

Resources