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();
});
});
Related
I can only use JavaScript to edit my checkout page, I am trying to hide and add styles to multiple elements using the least amount of characters.
Here's an example of one of the elements.
<div class="section section--remember-me shown-if-js">
<div class="content-box__row content-box__row--tight-spacing-vertical content-box__row--secondary">
Also trying to change the width of a button and make sure that the class.
<div class="step__footer" data-step-footer="">
This the parent of where the button is located in, and I want to make sure that the text thats also in this div isn't next to the button, but under it so I think I have to add style="display: inline-block;"
The button class is called
<button name="button" type="submit" class="step__footer__continue-btn btn ">
This is the code I have so far. I haven't been able to get it to hide multiple elements yet.
if (document.querySelector('.section--example') !== null) {
if (!element.classList.contains('example1')) {
element.classList.add('hidden');
};
document.getElementById("step__footer__continue-btn").style.width = "100%";
};
if-blocks do not need semicolons btw
document.querySelectorAll(".section--example:not(.example1)").forEach(hide);
function hide(element) {
element.classList.add("hidden");
}
To effect all element in an HTML class in jQuery it's like:
$(function(){
$('.sectionExample').css('background', '#000;');
});
or
$(function(){
$('.sectionExample').each(function(increment, element){
var current = $(element);
current.css('background', '#000;');
// this way is more versatile, if working with other Elements
});
});
I have a table where each visible row has a row beneath it whose visibility can be toggled by pressing a button. A live demo of this can be found here.
I'm really new to using jQuery and the problem I'm encountering is probably a simple fix to be honest. First of all, I want the togglable rows to be hidden by default and only shown when the button is clicked (now they show when the page is loaded). How can I do this?
To hide the rows I have the following:
$(document).ready(function(){
$("#button1").click(function(){
$(".trhideclass1").toggle();
});
});
$(document).ready(function(){
$("#button2").click(function(){
$(".trhideclass2").toggle();
});
});
I don't want to have to create a function for every button separately, so what is a better way to do this? My idea was to give a <button> and <tr> the same id and somehow make the button only toggle stuff with the same id, is this possible?
You can add a class to the buttons (like btn-toggle) and then traverse the DOM for getting the target element:
$(".btn-toggle").click(function() {
$(this).closest('tr').next('tr').toggle();
});
The values passed to the .closest and .next methods can be any valid selector. For understanding how these methods work you can refer to the jQuery documentations.
https://jsfiddle.net/mc1dkq6a/
You can set default hide in css
.trhideclass1,.trhideclass2{
display : none;
}
For more easy to handle you should change your button id only as number
HTML
<button id="1" class="btn btn-primary">Click me</button>
<button id="2" class="btn btn-primary">Click me</button>
JS
$(document).ready(function(){
$(".btn").click(function(){
current = $(this).attr('id');
$('.trhideclass'+current).toggle();
});
});
I have three buttons that change color when you hover (sprites) and I want to use those buttons so that when they are clicked on, different content will display.
I've gone through multiple tutorials / boards and nothing seems to work.
The buttons are displayed as follows:
<div id="buttons">
</div>
The divs where the content was placed (my last attempt) were as follows:
<div id="pages">
<div id="div1"><img src="..."></></div>
<div id="div2"><img src="..."></></div>
<div id="div3"><img src="..."></></div>
jQuery----
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var id = $(this).attribute("data-id"); // Using a custom attribute.
$("#pages div").hide(); // gather all the div tags under the element with the id pages and hide them.
$(".div" + id).show(); // Show the div with the class of .divX where X is the number stored in the data-id of the object that was clicked.
});
});
</script>
My anchors seem to be wrong. With this setup it just went to the top of the page. When using the anchor #1, #2, or #3 it would go to the div location but it would not hide or show the content. Frustrating.
The sprites are working fine. Now I'm trying to figure out how to make them clickable so that different content will display when each button is clicked (3 divs - under a parent div?). If anyone knows exactly how to do this I will be so thankful.
The content is largely images, and I am using Jupiter theme with a front-end editor so I don't know if it could be something with that. But nothing seems to be broken on the backend.
Also, if you can point me to a tutorial that will teach me how to make it so they animate in and out when clicked, that would be legit. Thanks again.
Check out my fiddle.
The code you posted had two main problems, confusing jQuery's data attributes with Javascript id's, and confusing the CSS selectors for classes (.) and ids (#). Here is the corrected html and javascript:
HTML
<div id="buttons">
Des
Brnd
Strt
</div>
<div id="pages">
<div id="div1"><p>This is 1</p></div>
<div id="div2"><p>This is 2</p></div>
<div id="div3"><p>This is 3</p></div>
</div>
Javascript
$("#pages div").hide();
$("a").click(function() {
var id = $(this).data("id");
$("#pages div").hide();
$("#div" + id).show();
});
you can Simple Use hide and show
Here Your Id for the button is Buttons
$("#ElementId" or ".Class").onClick(function(){
$("#OtherElement" or ".OtherElement").show()/hide()
});
You can Use .Toggle() to switch between states
so
$("#Buttons").click(function(){
$(".brnd").hide();
$(".des").show();
$(".Start").hide();
});
You can Also Use $("#Buttons").onclick(function(){ Instead of click depends on Your jquery version
See the Link May be you want this
Try this:
check tutorial here http://api.jquery.com/show/
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
$("#f,#s,#t").hide();
$(".des").click(function(){
$("#f").toggle();
});
$(".brnd").click(function(){
$("#s").toggle();
});
$(".strt").click(function(){
$("#t").toggle();
});
});
</script>
http://jsfiddle.net/9SabV/
i have updated my answer as you updated your html,script code.
check this also
Use # for id and . for class.
http://jsfiddle.net/mdgd7/
There is only one issue I found in your code ie
$(".div" + id).show();
here instead of "."(dot), you have to use "#".
You have to replace it with this:-
$("#div" + id).show();
because you are using "id" in "div", not "class".
UPDATE
You have have to remove this:
$("#pages div").hide();
instead you have add this to css file:-
#pages div{display:none;}
Here is the updated js script:-
$(document).ready(function() {
$("a").click(function() {
var id = $(this).attr("id"); // Using a custom attribute.
//$("#pages div").hide(); // gather all the div tags under the element with the id pages and hide them
$("#div" + id).fadeIn(); // Show the div with the class of .divX where X is the number stored in the data-id of the object that was clicked.
});
});
There are certain issues in you code. First of all you have not added data-id attribute to the anchor tags and tried referring them in you js code. The html5 "data-" attribute is used to store custom data inside the tag.The logic behind this is that any attribute with a "data- prefix" will not be processed and will be rendered as a data element.
Then the closures that you have added after the image tag are not necessary and syntactically wrong and is an error.
Here in your case, we can simply handle it with the "id" as there is not much need to use the data-attribute.
The simplified code will be like,
HTML
<div id="buttons">
ONE
TWO
THREE
</div>
<div id="pages">
<div id="div1">IMG 1</div>
<div id="div2">IMG 2</div>
<div id="div3">IMG 3</div>
</div>
JS
$("a").click(function() {
var id = $(this).attr("id"); //retrieving the id
$("#pages div").hide(); // hiding all elements
$("#div" + id).fadeIn(500); // showing the required one only
});
CSS
#pages div{
display:none;
}
Animations : I have added fadein animation. For simple fade in, fade out effects you can use jquery short hand animations like .slideDown() .fadeIn(), .animate(). There are more options available here : http://api.jquery.com/animate/
However you can add more customized animations using CSS3 animations which are more browser friendly. The criteria to choose is that, if you need more control over the animations and event tracking you can go for jQuery animations and otherwise CSS3 animations works like a charm.
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.
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();