jQuery - auto add toggle on element? - javascript

I have this code. Its for every single element. Is there a way to automate it? Because if I want to add element (job4 for example) I also need to add jQuery code.
$("#jobi1").click(function() {
$("#job1").fadeIn(300);
});
$("#jobi2").click(function() {
$("#job2").fadeIn(300);
});
$("#jobi3").click(function() {
$("#job3").fadeIn(300);
});

Give your job elements the same class and put the job identifier in a data-attribute, like this:
<button class="job" data-id="job1">job1<button>
<button class="job" data-id="job2">job2<button>
<button class="job" data-id="job3">job3<button>
And the javascript:
$('.job').on('click', function(){
var id = $(this).data('id');
$('#'+id).fadeIn(300);
});

Use a class and grab the ID from a data attribute
$(".job").on("click",function() {
$(this).data("target").fadeIn(300);
});
using
<div class="job" data-target="job1">...</div>

Related

How to run the same function (but class changes) on multiple IDs jQuery

I have the following jQuery code:
jQuery("#box1").focusin(function() {
jQuery(".grid_location1").show();
}).focusout(function () {
jQuery(".grid_location1").hide();
});
jQuery("#box2").focusin(function() {
jQuery(".grid_location2").show();
}).focusout(function () {
jQuery(".grid_location2").hide();
});
HTML
<input type="text" name="homepage_grid_box_1[box1]" class="box" id="box1">
<div class="grid_location grid_location1"> </div>
This repeats for every ID I have on the page i.e there is 15. I feel this cannot be the correct way to go about this and instead there has got to be a more efficient method. I wasn't sure if a loop with a counter would work and had a go but it wasn't working.
Any ideas?
You should better abandon the use of incremental id values like "box1", "box2", ...
Instead use a class "box" and assign that to those 15 box1, box2, ... box15.
For the same reason, incremental classes like "grid_location1", "grid_location2" are to be avoided. Just call them "grid_location". The context of where they are used, should be enough to isolate those that relate to a certain box element.
Either the box element contains the corresponding "grid_location" element(s), or you should create a container element (like a span) with a particular class ("container") that contains both one "box" element and the corresponding "grid_location" element(s).
Now that you added the HTML to your question, it is clear that those elements do not have a common parent, but are siblings. You can make it work with .next() as follows:
jQuery(".box").focusin(function() {
jQuery($(this).next()).show();
}).focusout(function () {
jQuery($(this).next()).hide();
});
A more reliable approach is to add container elements (with class "container"), like this:
<span class="container">
<input type="text" name="homepage_grid_box_1[box1]" class="box">
<div class="grid_location"> </div>
</span>
And then do:
jQuery(".box").focusin(function() {
jQuery(".grid_location", $(this).closest(".container")).show();
}).focusout(function () {
jQuery(".grid_location", $(this).closest(".container")).hide();
});
you can use with comma seperated id's
jQuery("#box1, #box2, #box3").focusin(function() {
jQuery(".grid_location1").show();
}).focusout(function () {
jQuery(".grid_location1").hide();
});

how to toggle between two ids rather than classes in jQuery

is there any way to toggle the styles of IDs in jQuery, the same way that toggleClass(); function do but with IDs and not classes.
this what is i tried with toggling classes and it works fine.
any solution with IDs
$(document).ready(function(){
$("button").click(function(e){
e.preventDefault();
$(".header-container").toggleClass("closed");
});
}):
i know that in such situations i should use classes but for flexibility and in some cases we have IDs . any suggestions
Using jquery you can edit the attrubite using .attr() :
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
$(document).ready(function(){
$("button").click(function(e){
e.preventDefault();
$(".header-container").toggleClass("closed");
if($(".header-container").attr('id')=='opened'){
$(".header-container").attr('id','closed');
}else{
$(".header-container").attr('id','opened');
}
var elid = $(".header-container").attr('id');
$(".header-container").html("i got an id now :"+elid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header-container">My id is empty</div>
<button>Edite Id</button>
since there is no function for toggling classes in jquery . you define one
create a new plugin to toggle between two functions
$(document).ready(function(){
jQuery.fn.idToggle = function(a,b) {
function cb(){ [b,a][this._tog^=1].call(this); }
return this.on("click", cb);
};
$('button').idToggle(
function(){
$('.header-container').attr('id','closed');
},
function(){
$('.header-container').attr('id','open');
});
});
.header-container { padding : 40px;}
#open{ background:#f08;}
#closed { background:#000;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header-container" id="open">
<div class="menu"> </div>
</div>
<button> click btn </button>

Class not working jQuery

So I more than one dynamicly generated elements with the same class name that I am trying to check input for in jQuery. Instead of it letting me click on both, it is just letting me click the first element generated.
Ex: I click on item_1 and it returns the item_1 id, but when I click on item_2 it doesn't return anyting.
HTML
<div id="item_1" class="resp"></div>
<div id="item_2" class="resp"></div>
JS - Jquery
$(".resp").on("click",() =>{
var id = $(".resp").attr("id");
console.log('attempting toggle' + id);
});
Firstly, you have to use normal function instead of arrow function (to avoid missing the context). Secondly - use this keyword to refer to the actually clicked element.
$(".resp").on("click", function() {
console.log('attempting toggle ' + this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item_1" class="resp">A</div>
<div id="item_2" class="resp">B</div>
This is because .attr('id') returns the value of the id attribute of the first matched element in the set.
Instead, use an old school function for the handler so the this value is equal to the clicked div, then get its id:
$(".resp").on("click", function() {
var id = $(this).attr('id');
console.log('attempting toggle ' + id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item_1" class="resp">First</div>
<div id="item_2" class="resp">Second</div>
What you're doing here is referencing the classname to obtain the id. This gathers the id of the first classname, which isn't what you desire. What you need to do is use the this keyword to correctly obtain the id.
After removing the arrow function and changing the internal code a bit, it should look like this:
$(".resp").on("click", function() {
var id = this.id;
console.log('attempting toggle: ' + id);
});
Also make sure you've correctly installed JQuery. Pick up your JQuery embed code from here.
Also remember to include your JQuery code before your JavaScript code.

Access elements inside a div outside of the current div

This is probably a very easy approach, however I haven't been able to figure it out.
My approach is to get all <img> elements that have the "expanded-image" class that are within the "img-preview" of my current "entry".
This is my html:
<div class="entry">
<div class="img-preview">
<img>
<img class="expanded-image" style="display:none;">
</div>
<div class="content">
[..]
[..]
<span class="more-text"></span>
[..]
[..]
</div>
</div>
And this is the JS I work with:
$('.content').each(function(event) {
$(this).find('span.more-text').click(function(event) {
// TODO
});
});
Firstly you don't need the each() at all as you can apply the click() event handler to all elements within a single selector.
To solve your issue you can use closest() to find the nearest parent .entry element to the clicked .more-text. From there you can find() all the .expanded-image elements. Try this:
$('.content span.more-text').click(function(event) {
var $imgs = $(this).closest('.entry').find('.img-preview .expanded-image');
// work with $imgs here...
});
$('.content').each(function(event) {
var $content = $(this);
$(this).find('span.more-text').click(function(event) {
$content.parent().find('.expanded-image'); // there you go
});
});
Use o combination of closest, prev and find
$('span.more-text').click(function(event) {
$(this).closest('.content').prev().find('.expanded-image');
});
You can use closest() to bubble up to find the parent given in the selector. Then from there you can navigate down to the required elements.
$(this).closest('.entry').find('.img-preview .expanded-image');
Also as Ron has suggested you dont have to loop and then bind the click events. You can simply do
$('.entry .content .more-text').click(function(){
$(this).closest('.entry').find('.img-preview .expanded-image');
})

Toggling between two buttons using jQuery

I've seen a few articles about this dotted around but I cant seem to get their solutions to work for me.
What I have are two buttons which control the show() and hide() states of different div's. On page load both of the div's are set to .hide() as the user doesn't need to see them until clicked.
So, I have two buttons a and b which currently work perfectly however you can show() both div's at the same time which I don't want to happen. The current code resembles
$('#a-div).hide();
$('#b-div).hide();
$('#a').click(function(){
$('#a-div).toggle(500);
});
$('#b').click(function(){
$('#b-div).toggle(500);
});
So how can I re-write this so that if #a-div is visible (already tried the .is(':visible') method) and #b is clicked nothing happens until #a-div is hidden again and vis versa?
Try this
$('#a-div').hide();
$('#b-div').hide();
$('#a').click(function(){
$('#a-div').toggle(500);
if($('#b-div').is(":visible"))
$('#b-div').hide();
});
$('#b').click(function(){
$('#b-div').toggle(500);
if($('#a-div').is(":visible"))
$('#a-div').hide();
});
probably you need to apply concept like this
$('#a-div).hide();
$('#b-div).hide();
$('#a').click(function(){
if ($('#b').isVisible)[you can check via css property as well]
{
$('#b-div).toggle(500); [or set css property visiblity:hidden]
$('#a-div).toggle(500);
}
else {$('#a-div).toggle(500);}
});
$('#b').click(function(){
if ($('#a').isVisible)[you can check via css property as well]
{
$('#a-div).toggle(500); [or set css property visiblity:hidden]
$('#b-div).toggle(500);
}
else {$('#b-div).toggle(500);}
});
What I ended up doing is this
$('#a-div').hide();
$('#b-div').hide();
$('#a').click(function(){
$('#a-div').toggle();
$('#b-div').hide();
});
$('#b').click(function(){
$('#b-div').toggle();
$('#a-div').hide();
});
For anyone who is interested. Prior to this I was making this much more complex than it needed to be.
Another solution is to create a universal function and pass the parameters of the shown and hidden objects. This way you can use the same method for future elements:
function toggleDivs($show, $hide) {
$show.toggle();
$hide.hide();
}
$("#b").on("click", function() { toggleDivs($("#b-div"), $("#a-div")); });
$("#a").on("click", function() { toggleDivs($("#a-div"), $("#b-div")); });
The only item missing is to initially hide the div objects, but I would add a css class to the objects to hide them.
HTML
<button id="a">Show A</button>
<button id="b">Show B</button>
<div id="a-div" class="hideDiv">A</div>
<div id="b-div" class="hideDiv">B</div>
CSS
.hideDiv { display:none; }
var $aDiv = $('#a-div');
var $bDiv = $('#b-div');
var $aBtn = $('#a');
var $bBtn = $('#b');
$aDiv.hide();
$bDiv.hide();
$aBtn.click(function(){
$aDiv.toggle(500, function(){
if($aDiv.is(":visible"))
$bBtn.prop("disabled",true);
else
$bBtn.prop("disabled",false);
});
});
$bBtn.click(function(){
$bDiv.toggle(500, function(){
if($bDiv.is(":visible"))
$aBtn.prop("disabled",true);
else
$aBtn.prop("disabled",false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a-div">div a</div>
<div id="b-div">div b</div>
<button id="a">btn a</button>
<button id="b">btn b</button>

Categories