Creating conditional statements for JQuery - javascript

I have a very novice question, so apologies if the answer to this is obvious.
I am using JQuery to toggle the contents of items based on whether the item has been clicked. I have been able to successfully implement the toggle feature.
I now need to have it load with the first two items set to show() with the rest set to hide(). I have given a unique class name to these first 2 items. I know that I can simply do a $('div.activeitem').show() and then hide thee rest, but I'd prefer to setup a condition.
I am a JQuery novice, so I don't know how to target these elements or their classes in a conditional statement. I've searched google but have been unsuccessful. I want a conditional that asks if the div "newsinfo" also has the class "jopen" then show(), else hide().
Thanks for your help. I have attached my code to help you understand the context of my question:
<script type="text/javascript">
$(document).ready(function(){
// Here is where I'd like to implement a conditional
$('div.newsinfo').hide(); // this would be part of my else
$('h5.newstoggle').click(function() {
$(this).next('div').slideToggle(200);
return false;
});
});
</script>

How about simply
$('div.newsinfo').each(function(){
if($(this).hasClass('jopen')){
$(this).show()
}else{
$(this).hide();
}
});

there is hasClass() function. Better way is using toggleClass().
For example:
$('div.blocks').click(function(){
$(this).toggleClass('class_name');
});
after first click class will be added, after second - removed... and so on ^^

JQuery has an .hasClass function.
i.e.
if($(".selectableItem").hasClass("selected")){
//remove selection
$(".selectableItem").removeClass("selected");
}else{
//remove the selected class from the currently selected one
$(".selectableItem .selected").removeClass("selected");
//add it to this one
$(".selectableItem").addClass("selected");
}

Why don't you add a default css to jopen class to display: block and the others to display: none ?
something like
.newsinfo {display: none}
.jopen {display:block!important}

Just use selectors. For example, if all divs with the class "newsinfo" are visible by default:
$("div.newsinfo:not(.jopen)").hide();
If they're all hidden by default:
$("div.newsinfo.jopen").show();

Related

.addClass() jQuery how to specify the CSS

I have a div and I want to put a display none when I click on it. I am using bootstrap4 and It has a css style called "d-none" that put display none to an element.
For that, I have put this in the .js:
$("#div").on("click", function(e, m) {
alert("Enter OK");
$("div").addClass("d-none");
});
but I donĀ“t know how to specify that it must take the style form the bootstrap.min.css, because I am using more than one css at the same time.
I have tried this:
$("#div").on("click", function(e, m) {
alert("Enter OK");
$("div").addClass("../css/bootstrap.min.css/d-none");
});
But it doesn't work.
How can I specify the CSS?
add # in $("#div").addClass("d-none");
As per my understanding, the class .d-none is applying to the div on click event but other CSS file overrides it. There are other bootstrap properties also as .hide or .hidden (check these as per your bootstrap version). you can apply that.
If still it is not working - you can create your own unique class and set property as display:hidden; and add the same class instead of .d-none
also don't forget to add this line:
$(this).addClass("d-none"); instead of $("div").addClass("d-none");, because it will apply to the particular element that you want to hide.
Hope this may help you.
You can trigger self element by $(this). As below answer if you want to add class or hide #div on self click you can do as below code.
$("#div").on("click", function(e, m) {
alert("Enter OK");
$(this).addClass("d-none"); // If you want to add class
$(this).hide(); // if you want to hide this dive
});

Store jQuery in a variable

I've got an FAQ page I'm building. Next to the question, there is a plus sign to expand the content. On click, I've added the class active, but there are many questions, and I don't want to repeat the same jQuery snippet for each question. I've figured out how to find the parent ID but I'm having trouble storing it in an variable to reuse in the jQuery script.
What I want to be able to do:
var element = $(this).parent().parent().attr('id')
$('.expand').click(function(){
$('element .expand').toggleClass('active')
})
Is there a way to do this? I get undefined when I do this:
$('.expand').click(function(){
console.log(element)
});
You can use the find() function to locate children of a selected element:
var element = $(this).parent().parent().attr('id')
$('.expand').click(function(){
$("#" + element).find('.expand').toggleClass('active')
});
However, looking at your code, it seems like you just want to toggle the "active" class of the clicked element. If that is the case, you can do this much more simply without a variable at all:
$('.expand').click(function(){
$(this).toggleClass('active')
});

how do i remove classes with jQuery?

how do i remove classes with jQuery?
I have this "template" i am working on and i want a "settings" box to the left where the user can change the "color scheme" of the navigation.
I have like 5-10 colors and i cant get it to work.
$(".color-orange").click(function () {
$("#nav").addClass("color-orange");
});
How can i then remove the class "color-orange" and add a new class if someone clicks on green?
Well i used this..
$(".color-green").click(function () {
$("#nav").removeClass("color-orange");
$("#nav").addClass("green");
});
But that just takes orange away. And will not work if you clicked another color..
Sorry for my english, and yes. Its my first time here :)
Kind Regards / Albin
Try this:
$("#nav").removeClass().addClass("green");
Without arguments removeClass will remove all the classes.
Also don't reselect $("#nav") again and again, use method chaining, this increases performance.
The below code will simply overwrite existing classes to whatever you set (in this case "green").
$("#nav").attr("class", "green");
Since this has gained enough upvotes, I'll tell you why this is kind of better answer than the above one. The one with removeClass().
First, you get the required element, that is $("#nav").
Then, you call a property of JQuery, removeClass().
Then, you again call another property of JQuery, addClass().
In the solution I suggested:
First, you get the element, then call the propery attr(), and that's it.
So, it's one step lesser.
How about this
$('[class^="color-"]').each(function() {
$("#nav").removeClass().addClass($(this).attr("class"));
}
or as xFortyFourx pointed out:
$('[class^="color-"]').each(function() {
$("#nav").attr("class",$(this).attr("class"));
}
Alternative - if I assume you have
.green { color:green; .... } /* for the nav */
.color-green { color:green; .... } /* for the settings */
you can do
$('[class^="color-"]').each(function() {
$("#nav").attr("class",$(this).attr("class").replace("color-",""));
}
Use removeClass and do not pass any class to removeClass and it will remove all classes that element has.
$(".color-green").click(function () {
$("#nav").removeClass().addClass("green");
});
$(".color-green").click(function () {
$("#nav").removeClass("color-orange");
$("#nav").removeClass("next-color");
$("#nav").removeClass("another-color");
$("#nav").removeClass("yet-another-color-but-green");
$("#nav").addClass("green");
});

using $(this) jquery to change another element

So, I know how to change an attribute for the same element you hover over...
$(".click2play").mouseover(function()
{
$(this).css({'visibility' : 'hidden'});
});
question Can I do the same thing but to affect another element only within the same 'click2play' div that was hovered?
maybe like?
$(".click2play").mouseover(function()
{
$(this).(#someotherdiv).css({'visibility' : 'hidden'});
});
Thanks everyone!
This code targets a div, within the current .click2play element. I believe that's what you were asking for :)
$(".click2play").mouseover(function() {
$('div.class_name', this).css({'visibility' : 'hidden'});
});
not very clear from the ques what you wanna do so ill ans for all the options i can guess of
1.if you wanna hide all the elements of class .click2Play then use
$('.click2Play').hover(function(){$('.click2play').hide()});
2.if you want to just hide the current element of all the elements having this class use
$('.click2Play').hover(function(){$(this).hide()});
3.if you wanna generalize it then you can use.selector property of the jquery object so that you would be able to use it like
$('.click2Play').hover(function(){$($(this).selector).hide()});
so now if you will change the class name from .click2Play to some other class it will work nicely and will hide all the elements of that class.
4. if you want to hide some element inside that of current element then
$('.click2Play').hover(function(){$(this).children('selector_of_child').hide()});
5.if all the elements of this class have an element inside them having some other class and you wanna hide them all then simple use each like this
$('.click2Play').hover(function(){$('.click2play').each(function(){$(this).children("selector_Of_Child").hide()})});
I would do like this:
$(".click2play").mouseover(function(){
$(this).hide();
});
But maybe it isn't what you want to do?
I suppose this :):
$(".click2play").mouseover(function(){
$(this).css({'visibility' : 'hidden'});
});
or better
$(".click2play").mouseover(function(){
$(this).hide();
});
You want to change some other div? Why would you need $(this)?
$(".click2play").mouseover(function(){
$("#someotherdiv").hide();
});
To change a single css attribute you can do:
$(".click2play").mouseover(function(){
$(this).css('visibility', 'hidden');
});
I hope it helps
(consider to see this link: http://marakana.com/bookshelf/jquery_tutorial/css_styling.html )
I believe most of the answers didn't payed attention to the question, which asks about removing a class. Here is the answer to both questions:
$('.click2play').bind('mouseenter mouseleave', function () {
$(this).removeClass('click2play'); // This line removes the current object's class click2play
$('jQUerySelector').removeClass('click2play'); // This will remove another element's class click2play
});

How can I use multiple Floating Help Dialogue by using 'class' instead of 'id'?

I need to use multiple floating help dialog boxes in a page. I have tried it by using 'display:block' and 'display:none' and used ID in javascript. I cannot use classes since I have multiple of them on the same page and if I use classes then all of them will be displayed/hide at the same time. However, as the number of help items are increasing in the page, I have to go back to the javascript and add more lines ...
for example:
$(document).ready(function() {
$("#help-icon1").click(function() {
$('#help-details1').css('display', 'block');
});
$("#help-icon2").click(function() {
$('#help-details2').css('display', 'block');
});
$("#help-icon3").click(function() {
$('#help-details3').css('display', 'block');
});
});
Each of them also have close icons and they should be disappeared if clicked on that close icon or clicked anywhere in the page. That means I have to write javascript functions 3 times for all the different close icons.
I tried to rely on jquery's "next" feature, but since there are many layers (div/p/span) in between the areas where the help icon is places and the help text, it becomes problamatic. Any idea or any better way to resolve this?
Thanks in advance.
I'm not quite sure I understand what you are looking for, but you can set up all the click handlers in one step, and have each one refer to itself in the handler:
jQuery(".help-icon").click(function() {
jQuery(this).css('display', 'block');
});
You can add additional class names to an element.
A div can be hidden by default, and a new class can be appended to it - to "overrule" the previous style (Hence the name Cascading Style Sheets)
<div class="hidden exception"></div>
If an element is clicked, you can append a new classname like so:
$('.target').addClass('newclass');
more info:
http://api.jquery.com/addClass/
I've not done it using JQuery but what you need is "unobtrusive javascript".
It does get done by using a class. Say you have images you all want highlighted:
<img src="pic1.png" onMouseover="this.src='hi_pic1.png';" />
so they all have the same behaviour. Give them a class:
<img src="pic1.png" class="hi" />
Then at load time, on in the script at the end of your page, yahoo-style, you write an initialisation to
- grab every element of the class
- add the event(s) you want
- set the event to use the appropriate data, e.g. by using this and by using systematic names like pic1 -> hi_pic1.
Hope this helps,
Charles
Have you tried the jQuery .each function?
EDIT: Like the following
$(".help-icon").each(function(idx, elm){
elm.click(function(){
...
})
});
If all of your help icons have the same class you can use jQuery's each function to loop through them, retrieve the associated id, replace "icon" with "detail" in the id (so #help-icon3 would become #help-detail3), and then use that to update the panel. Something like:
$(".help-icon").each(function() {
var detailsId = $(this).attr("id").replace("icon", "details");
$("#" + detailsId).css('display', 'block');
});
Let's just ASSUME that you need to use IDs for some unknown reason. Here's your answer to combine efforts:
$("#help-icon1").add("#help-icon2").add("#help-icon3").click(function() {
$(this).css('display', 'block');
});
Which equates to:
$("#help-icon1, #help-icon2, #help-icon3").click(function() {
$(this).css('display', 'block');
});
But really, you don't need to use unique IDs like this without some pretty good reasons.

Categories