I am trying to convert a lot of JavaScript to jQuery and I have a task that I believe has a simple jQuery shortcut, but I don't know what it is and I haven't been able to find an example.
I have a page with many toggled divs. They are in the form that follows where ### is a unique integer for each pair.
<button class='togglebutton' onclick="toggle('div###');">+</button>
<div id='div###'>...some text...</div>
I'd assume the shortcut is something like:
$('.togglebutton').onclick(function() {
var divid = '#div'+?????;
$(divid).toggle();
});
My theory... if I give each button an id, such as 'button###', then I can use substring to get the value after the word 'button', something like:
$(this).id().substring(6,3);
Obviously, that didn't work. So, I figured that I should ask if there is a simple shortcut in jQuery to pair a showhide button with a separate div.
You may want to do this no matter where your div locates http://jsfiddle.net/tg5op333/25/
HTML
<button class='togglebutton' data-id="1">+</button>
<div id='1' style="display:none">...some text...</div>
<button class='togglebutton' data-id="2">+</button>
<div id='2' style="display:none">...some text...</div>
<button class='togglebutton' data-id="3">+</button>
<div id='3' style="display:none">...some text...</div>
<button class='togglebutton' data-id="4">+</button>
<div id='4' style="display:none">...some text...</div>
JS:
$('.togglebutton').click(function() {
$("#"+ $(this).data('id')).toggle();
});
If the HTML is ordered like you show in your question, then use:
$('.togglebutton').click(function() {
$(this).next().toggle();
});
$('.togglebutton').click(function() {
$(this).next().toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class='togglebutton'>+</button>
<div id='div1'>...some text...</div>
<button class='togglebutton'>+</button>
<div id='div2'>...some text...</div>
<button class='togglebutton'>+</button>
<div id='div3'>...some text...</div>
Two ways:
1) You can use some common class attribute to all dives and select all using that.
Or
2) Or else you can use this wildcard selector :
$("[id^=div]")
It gives you all divs whose id starts with div.
Related
Trying to remove children DIV elements of a parent with certain attribute. I have it half working, but with the below code, it doesn't find the children
HTML
<div id="PremiumGiftContainer" class="PremiumGiftContainer">
<div class='message' is-vip='false'>
<p>FALSE</p>
</div>
<div class='message' is-vip='false'>
<p>FALSE</p>
</div>
<div class='message' is-vip='true'>
<p>TRUE</p>
</div>
</div>
<button id="button">Remove</button>
JQUERY
$("button").on("click", function(){
remove_element();
})
function remove_element(){
$('#PremiumGiftContainer').children(function () {
$("[is-vip]").each(function(){
if($(this).attr('is-vip')=='true'){
$(this).fadeOut();
}
});
})
}
FIDDLE
If I remove the $('#PremiumGiftContainer').children... section, it works, but I was trying to limit the scope of the search that needs to happen to find the correct switches.
Is what I'm trying to do achievable?
children() does not accept a function, it takes a selector. As such you can simply use an attribute selector and then call fadeOut() on the resulting elements.
Also note that you should not create your own non-standard attributes on elements. If you want to store custom data with an element, use a data-* attribute.
$("button").on("click", function() {
remove_element();
})
function remove_element() {
$('#PremiumGiftContainer').children('[data-is-vip="true"]').fadeOut();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="PremiumGiftContainer" class="PremiumGiftContainer">
<div class="message" data-is-vip="false">
<p>FALSE</p>
</div>
<div class="message" data-is-vip="false">
<p>FALSE</p>
</div>
<div class="message" data-is-vip="true">
<p>TRUE</p>
</div>
</div>
<button id="button">Remove</button>
Can do this with one selector using an attribute selector
$('#PremiumGiftContainer > [is-vip=true]').fadeOut()
DEMO
$(document).ready(function(){
$("button").click(function(){
$("#answer").toggle(1000);
});
});
this only works for the IDs "answer" and "button", the challenge for me its getting multiple pairs of these IDs (answer1 - button1, answer2 - button2, and so on) to work with this single function
You haven't included the relevant HTML so I can only guess/assume what it might look like in my demo/example.
For multiple elements it is best to use a class to group them.
$(document).ready(function() {
$(".answerTog").click(function() {
$(this).prev('.answer').toggle(1000);
});
});
.Question {
display: block;
margin-bottom: 5px;
}
.answer {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Question">
<input type="text" placeholder="Question One" />
<span class="answer">Question One Answer.</span>
<button class="answerTog">See Answer</button>
</div>
<div class="Question">
<input type="text" placeholder="Question Two" />
<span class="answer">Question Two Answer.</span>
<button class="answerTog">See Answer</button>
</div>
<div class="Question">
<input type="text" placeholder="Question Three" />
<span class="answer">Question Three Answer.</span>
<button class="answerTog">See Answer</button>
</div>
If your button is before the answer then you can simply use
$(this).next('.answer').toggle(1000);
$(this) will target the specific element used to trigger the function call, in this instance the button being clicked.
.prev('.answer') will target the previous element with the class name of answer
.next('.answer') will target the next element with the class name of answer
JsFiddle Demo
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
You are currently using an ID property to call that button ($('#')) You want to call them by classes.
IDs should be unique and only used in 1 DOM element.
Trying to use ID the script will only pick the 1st element it comes across; and the code will only work for that one button.
With classes you create an Object for all of your elements, with jQuery you just have to call the element by its class, and run the code normally - I note this because in JS you would have to add the index to the element call.
For example:
<canvas id="main"></canvas>
<div class="elem"></div>
<div class="elem"></div>
<div class="elem"></div>
<script>
var canvas = $('#main'), // return 1 element
elements = $('.elem'); // return 3 elements
</script>
So for anything that involves multiple elements you must call them by class or tag name.
In vanilla JS you would look at something like this:
<script>
var elem = document.querySelectorAll('.elem');
console.log(elem[0]);
</script>
So, your code would then just need to call those elements by class; and you can set custom classes for different purposes.
$(document).ready(function() {
var btns = $('.btn');
btns.click(function() {
btns.toggle(1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Button</button>
<button class="btn">Button</button>
<button class="btn">Button</button>
<button class="btn">Button</button>
<button class="btn">Button</button>
I need some help. As you will see in my fiddle, I am attempting to use buttons to populate a single container div with content from multiple hidden divs, depending on which button is clicked. The problem I am having is, I don't know how to access the actual content in the hidden divs to populate the container div. As of now, I am using the id attributes for the hidden divs to demonstrate which div content I would like to display in the container.
I've seen a few other posts with link <a> attributes referencing hidden content, but none so far using a button element with click functionality to change div content.
jQuery(function ($) {
$('#button1').click(function () {
$('#info').empty();
$('#info').prepend('#option1');
});
$('#button2').click(function () {
$('#info').empty();
$('#info').prepend('#option2');
});
$('#button3').click(function () {
$('#info').empty();
$('#info').prepend('#option3');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button id="button1">Button 1</button></li>
<li class="buttons"><button id="button2">Button 2</button></li>
<li class="buttons"><button id="button3">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info"></div>
</div>
<div id="hiddenDivs" style="display:none;">
<div class="info" id="option1">Box</div>
<div class="info" id="option2">Google Drive</div>
<div class="info" id="option3">Box</div>
</div>
Here is my fiddle
Here's a version that uses jquery data attributes. It reduces the redundancy and complexity and can be configured easily.
<body>
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button id="button1" data-link="option1">Button 1</button></li>
<li class="buttons"><button id="button2" data-link="option2">Button 2</button></li>
<li class="buttons"><button id="button3" data-link="option3">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info">
</div>
</div>
<div id="hiddenDivs" style="display:none;">
<div class="info" id="option1">Box</div>
<div class="info" id="option2">Google Drive</div>
<div class="info" id="option3">Box</div>
</div>
</body>
<script>
$('.buttons button').click(function (){
$('#info').empty();
$('#info').html($("#" + $(this).data('link')).html());
});
</script>
Example : https://jsfiddle.net/yvsu6qfw/3/
It sounds like maybe you were looking for using the button itself to populate data built into the button with a data attribute or something? If so you can do something like this:
HTML
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button data-info="Box">Button 1</button></li>
<li class="buttons"><button data-info="Google Drive">Button 2</button></li>
<li class="buttons"><button data-info="Box">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info"></div>
</div>
jQuery
$(document).ready(function (){
$('#button-column button').click(function (){
$('#info').html($(this).attr('data-info'));
});
});
If you want the first button to load the content from the first hidden div etc. without relying upon using the id attributes, you can use the .index() method. When you pass this as an argument it will return the index value of the click event target in the collection $("#button-column .buttons :button"). Afterwards you can pass the index value to the .get() method to retrieve the corresponding element from the collection of hidden divs $("#hiddenDivs .info").
$().ready(function(){
$("#button-column .buttons :button").on("click", function(){
$('#info').empty();
var clickedIndex = $("#button-column .buttons :button").index(this);
var hiddenInfo = $("#hiddenDivs .info").get(clickedIndex);
$('#info').prepend( $(hiddenInfo).text() );
});
});
you can use html function, without parameter gets the content of the element
with parameter replaces the content with the string parameter
$(document).ready(function (){
$('#button1').click(function (){
$('#info').html( $('#option1').html() );
});
$('#button2').click(function (){
$('#info').html( $('#option2').html() );
});
$('#button3').click(function (){
$('#info').html( $('#option3').html() );
});
});
In your code example, you do for example:
$('#info').prepend('#option1');
What you instruct to do here, is adding a text string '#option1' to an element with ID info.
What you intend to do is prepending the content of ID option1 to the element with ID info. You could do something like this instead:
$('#info').prepend($('#option1').html());
Another approach could be (but I don't know if that's relevant for you) to not clone content (since it costs you repaints) but toggle the specific elements instead. For example:
$('#option1,#option2').hide();
$('#option3').hide();
And yet another one: use data-attributes on your buttons:
Button 1
Button 2
<div id="info">
</div>
And the JS:
$('.button').on('click', function(event) {
event.preventDefault();
$('#info').html($(event.currentTarget).attr('data-text'));
});
Don't repeat yourself! To get the number out of an ID replace with "" all that is not a number using RegExp \D.
Using number from ID
Than, to get the actual content you can use $("#option"+ num).html() or $("#option"+ num).text() methods:
jsFiddle demo
jQuery(function ($) {
$('.buttons button').click(function () {
var num = this.id.replace(/\D/g,"");
$("#info").html( $("#option"+ num).html() );
});
});
Target element using data-* attribute
Alternatively you can store inside a data-* attribute the desired target selector ID:
<button data-content="#option1" id="button1">Button 1</button>
and than simply:
jsFiddle demo
jQuery(function ($) {
$("[data-content]").click(function () {
$("#info").html( $(this.dataset.content).html() );
});
});
http://api.jquery.com/html/
http://api.jquery.com/text/
If the expectation is to get same indexed hidden div content, Then the below code should work.
$(document).ready(function (){
$('.buttons button').click(function (){
$('#info').empty();
var index = $('.buttons button').index($(this));
$('#info').html($('.info:eq('+index+')').html());
});
});
I am using bootstrap v3.3.5 in my application and wanted to include collapse function such that, when user clicks on a link, div below it toggles. Referring to answer in this Can you specify a "data-target" for Bootstrap which refers to a sibling DOM element without using an ID? I was able to achieve similar result as my requirement, in the below fiddle link
https://jsfiddle.net/szp1cg0k/, which is using bootstrap v2.1.1.min.js and v2.1.1.min.css
But in the same fiddle when I include bootstrap v3.3.5.min.js and v3.3.5.min.css reference the toggle/collapse functionality doesn't work here, neither throws any error
updated JS https://jsfiddle.net/ohoLxap6/2/
html code:
<fieldset class="fsStyle">
<legend class="legendStyle">
<a data-toggle="collapse-next" data-target=".demo" href="#">Activity Log Filter Criteria4</a>
</legend>
<div class="demo" >
<div class="col-md-2">
<label for="activity_from_date" class="labelStyle">Activity From Date:</label>
</div>
<div class="col-md-4">
<input name="fromDate" maxlength="10" size="11" tabindex="59" value="" onblur="javascript:DateFormat(this,event,true);" class="textInput" id="activity_from_date" type="text">
</div>
</div>
</fieldset>
script:
$('body').on('click.collapse-next.data-api', '[data-toggle=collapse-next]', function() {
console.log($(this).parent());
var $target = $(this).parent().next()
console.log($target);
$target.data('collapse') ? $target.collapse('toggle') : $target.collapse()
});
Can anyone give me some hint where I am going wrong ?
UPDATE:
I am aware of the collapse function of bootstrap, I have multiple divs in my form and I want to include collapse function on most of the divs. One way to achieve this is
<div data-toggle="collapse" data-target="#demo1">
<div id="demo1">
<p>demo 1 ......</p>
</div>
<div data-toggle="collapse" data-target="#demo2">
<div id="demo2">
<p>demo 2 ......</p>
</div>
But I dont want to use ids, instead I want to specify class. The reason being, I have jqtree at backend and I have to include clone function as well, so using ids would mean after cloning I need to take care of ids of cloned child node div. Hence want to use class instead , something like below
<div data-toggle="collapse" data-target=".demo">
<div class="demo">
<p>demo 1 ......</p>
</div>
<div data-toggle="collapse" data-target=".demo">
<div class="demo">
<p>demo 2 ......</p>
</div>
Got this working. I have updated the fiddle accordingly. https://jsfiddle.net/ohoLxap6/3/
$('body').on('click.collapse-next.data-api', '[data-toggle=collapse-next]',
function() {
//console.log($(this).parent());
var $target = $(this).parent().next()
console.log($target);
$target.data('bs.collapse') ? $target.collapse('toggle') :
$target.collapse()
});
Why would you write your own code for a existing Bootstrap function? Following code is an example of the latest Bootstrap version collapse method:
<button class="btn" data-toggle="collapse" data-target="#demo">Collapsible</button>
<div id="demo" class="collapse">
Some text..
</div>
Docs: http://getbootstrap.com/javascript/#collapse
UPDATE:
According to your new question, collapsing using classes, I have created a custom script:
$('[data-toggle="collapse"]').click(function() {
var $target = $(this).data('target');
var $target = $($target);
$target.data('bs.collapse') ? $target.collapse('toggle') :
$target.collapse()
});
Now all classes inside the data-target attribute will get toggled. https://jsfiddle.net/ohoLxap6/4/
I am using a jQuery function to add/remove a class to the clicked element, which works just fine. However when that element is clicked, I am trying to change the text of an HTML link and I cannot seem to get it working. The HTML link is located within the <span> element further down the page.
When <button id="people"> hasClass('user_view_active') the HTML link should display "People" when <button id="jobs"> hasClass('user_view_active') the HTML link should display "Jobs".
<script type="text/javascript">
$(document).ready(function() {
$('button').click(function(){
$('button').each(function(){
$(this).removeClass('user_view_active');
});
$(this).addClass('user_view_active');
});
if ($('#people').hasClass('user_view_active')){
$('.title').find("a").attr("href").text(text.replace('People'));
}else{
$('.title').find("a").attr("href").text(text.replace('Jobs'));
}
});
</script>
</head>
<body>
<div id="container">
<header>
<img src="images/header-name.png" width="200px" style="display: inline; margin-bottom: -10px;"/>
<button id="jobs" class="user_view">Jobs</button>
<button id="people" class="user_view_active user_view">People</button>
<div class="header_search_wrapper">
<form action="" method="POST">
<textarea class="header_search" name="app_search" placeholder="Search people, jobs, or companies" style="width: 430px;"></textarea>
<input type="submit" class="share_btn" value="Search">
</form>
</div>
</header>
<div id="main" role="main">
<!--! begin app content -->
<div class="right_sidebar">
<span class="right_title">Connection Suggestions</title>
</div>
<span class="title">Recent Updates >> People</span>
To replace the text within a link you can use the jQuery .text() function. This function can also get the text value and also set the text value - as is shown in the example below -
if ($('#people').hasClass('user_view_active')){
$('.title').find("a").text('People');
}else{
$('.title').find("a").text('Jobs');
}
This code would have to be wrapped in the callback function of the click event to work -
$(document).ready(function() {
$('button').click(function(){
$('button').removeClass('user_view_active');
$(this).addClass('user_view_active');
if ($('#people').hasClass('user_view_active')){
$('.title').find("a").text('People');
}else{
$('.title').find("a").text('Jobs');
}
});
});
Now each time the button is clicked, you can check for the existence of the user_view_active class on the #people element.
Okeydokey ?
Are you sure those are the right tags ?
<span class="right_title">Connection Suggestions</title>
Are you sure an <a> element inside a <button> element is a good idea?
<button id="jobs" class="user_view">Jobs</button>
role="main" is'nt a valid attribute, but will probably work anyway.
This just seems easier:
$(document).ready(function() {
$('button').on('click', function(){
$('button').removeClass('user_view_active');;
$(this).addClass('user_view_active');
$("a", ".title").text(this.id);
});
});
FIDDLE
Try this way:
$('#people').toggleClass('user_view_active').html($('#people').hasClass('user_view_active')?'People':'Jobs');