Function for adding and removing style on click and unfocus - javascript

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.

Related

JavaScript focus a particular element with div class, not div id declaration

The following function can focus on an element with an id declaration:
function setFocus() {
document.getElementById("focus").focus();
}
But how can one focus on an element with a classname declaration. Use case would be previously in the code where the element we want to focus on is already stored from the dom (i.e., const element = document.querySelectorAll('.a-class-name')[0]) type of scenario?
Does the element have a tab index? You cannot focus a non input element unless it has a tab index. Use tabindex="-1" for elements like divs and spans. Then call the .focus() method on the element. -1 will allow you to focus with the focus method but wont get focus when move the focus around with the keyboard and pressing tab.
document.getElementById('btn').addEventListener('click', function() {
document.querySelectorAll('.focus_me')[0].focus();
});
<span class="focus_me" tabindex="-1">Focus me</span><br>
<button id="btn">Click to focus</button>
element.scrollIntoView(true) will do what you are needing.
document.getElementsByClassName('className') would always return multiple elements because conceptually Classes are meant to be applied to multiple elements. If you want only the first element in the DOM with that class, you can select the first element out of the array returned, as you did.
var elements = document.getElementsByClassName('className');
var requiredElement = elements[0];
OR
var requiredElement = document.querySelector('.className');
Then as #j08691 mentioned in the comments use
function setFocus() {
requiredElement.focus();
}
If the one with getElementById works, then there is no reason for this to not.
Happy coding. :)

Bind an html event to a function

How do I bind an html event such as onclick to a function myFunc(e){}?
I do not want to use document.getElementByClass or Id.
I do not want use jQuery.
Try this:
document.getElementsByTagName('body')[0].addEventListener('click', function(){alert("you clicked on the page")})
This adds an event listener to the body tag. Once you click on the page, it will fire the alert function.
You can get the elements by either class name, id and/or tag name:
document.getElementById('someId')
document.getElementsByClassName('someClassName')
document.getElementsByTagName('body')
Keep in mind, the "getElementsByClassName" and "getElementsByTagName" return arrays, so you might want to add the index like this
getElementsByTagName('body')[0]
document.getElementsByClassName('someClassName')[1]
...
If it's still the 1990s where you are and jQuery hasn't been invented, then sure:
<div onclick="myFunc">
</div>
First you must find the element on the page, for example var element = document.getElementById('clickme'), then you must add a listener to the click event element.addEventListener('click',function)

how to find the class name of 'deepest' div in javascript/jquery?

I am aware that e.target contains the info of the element just below the cursor, but what if I want to know the class name of the div which has a table>tr>td>button in it and I'm clicking that button inside that td. I know this events bubbles up and there should be a way to find out if the div exists in that bubbling levels. Any help.
Scenario: button is inside a modal window. How do I find the modal windows class name on click of the button inside it.
Use .closest() to traverse up the DOM to the nearest match:
var parentDiv = $(yourButton).closest('div');
Or in the button's click:
$(yourButton).click(function() {
var nearestParentDiv = $(this).closest('div');
// And read its class
console.log(nearestParentDiv.attr('class'));
});
The selector .closest() accepts can of course be more specific than this, so if if the modal window <div> has some known class but you need to inspect its other classes, you should use the more specific selector.
Yes as you say the event will bubble up to your div, so just make the div handle the event with .on() , like this:
$('#yourdiv').on('click',':button',function(e) {
alert( $(e.delegateTarget).attr('class') );//alerts the classes of #yourdiv
alert( $(this).attr('id'));//alerts the id of the clicked button (if have one)
});
UPDATE:
Fixed obtaining the reference to the original div where the event was attached. With event.delegateTarget from the Event object . Thanks Cristophe and Kevin B. for spotting the error.
See working demo
You can use .parent() to get the parent div attributes like id: http://jsbin.com/ololad/1/edit
$('button').click(function(){
console.log($(this).parent().attr('id'));
});

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.

Hiding elements with a specified id

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();

Categories

Resources