how to toggle between two ids rather than classes in jQuery - javascript

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>

Related

Dynamic jquery. How to apply jquery only to certain elements?

Hey guys I am doing a simple hover color change however I found myself repeating jquery can it be done so that when btn is hovered the corresponding service-icon changes color? Without repeating as below.
$(document).ready(function() {
$('.btn-1').hover(function() {
$('.service-icon-1').css('color', '#05FAB8');
},function(){
$('.service-icon-1').css('color', '');
});
});
$(document).ready(function() {
$('.btn-2').hover(function() {
$('.service-icon-2').css('color', '#05FAB8');
},function(){
$('.service-icon-2').css('color', '');
});
});
$(document).ready(function() {
$('.btn-3').hover(function() {
$('.service-icon-3').css('color', '#05FAB8');
},function(){
$('.service-icon-3').css('color', '');
});
});
Without your HTML, chances are that my snippet may be unrelevant. I assume the icons are not child of each button because that would be too easy.
Using JS, I would use a data-attribute to store the service number on both button and icon... and use that data attribute value in an attribute selector.
Notice the usage of template litteral: backticks ` and ${}.
$(document).ready(function() {
$('.btn').hover(function() {
let serviceNb = $(this).data("service")
$(`.service-icon[data-service=${serviceNb}]`).css('color', '#05FAB8');
},function(){
let serviceNb = $(this).data("service")
$(`.service-icon[data-service=${serviceNb}]`).css('color', '');
});
});
div{
margin: 1em;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class="service-icon" data-service="1"><i class="fa fa-tools"></i></span>
<span class="service-icon" data-service="2"><i class="fa fa-hand-holding-usd"></i></span>
<span class="service-icon" data-service="3"><i class="fa fa-trash"></i></span>
</div>
<button class="btn" data-service="1">Repair</button>
<button class="btn" data-service="2">Sell</button>
<button class="btn" data-service="3">Trash</button>
1) Put "btn-1", "btn-2, "btn-3" in the ID of your buttons, instead of class.
2) Put a common class in the buttons. (e.g. "btn")
3) Use $(".btn").hover ONCE
4) Inside you can use $(this).prop("id") to get the actual ID (e.g. "btn-1")
5) Extract the "1" from that ID that you retrieve. Put it in var btnIdNo.
6) Use $(`.service-icon-{btnIdNo}`).css(blah)
Always try to put unique identifiers in ID instead of CLASS. Keep CLASS for ways to identify a 'type' of element.
Something like this maybe:
$(document).ready(function() {
$('.btn-1, .btn-2, .btn-3').hover(function() {
if ($(this).is('.btn-1')) {
$('.service-icon-1').css('color', '#05FAB8');
} else if ($(this).is('.btn-2')) {
$('.service-icon-2').css('color', '#05FAB8');
} else {
$('.service-icon-3').css('color', '#05FAB8');
}
},function(){
$('.service-icon-1, .service-icon-2, .service-icon-3').css('color', '');
});
});

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>

jQuery - auto add toggle on element?

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>

jquery : how to apply same changes inside mulitple container with same class name

i am trying to move a .details outside of .buttons
<div class="product-actions">product 1
<div class="buttons buttons_3 group">buttons
<a class="details" title="Détails" rel="nofollow" >link</a>
</div>
</div>
<div class="product-actions">product 2
<div class="buttons buttons_3 group">buttons
<a class="details" title="Détails" rel="nofollow" >link</a>
</div>
</div>
this do the trick
if ($('.product-actions').length )
{
$('.product-actions').prepend("<div id='new_details_location'></div>");
$(".details").prependTo("#new_details_location");
$('.buttons_3').attr('class','buttons buttons_2 group');
}
the problem is there is more than one product and all a.details get moved to the first product div instead of being prepend at the beginning of each div .product-actions:
http://jsfiddle.net/upKhq/2/
any idea?
Try this FIDDLE
$('.product-actions').each(function () {
$new = $(this).prepend("<div class='new_details_location'></div>");
$(".details", $(this)).prependTo($new);
$('.buttons_3', $(this)).attr('class', 'buttons buttons_2 group');
});
You made a few mistakes:
your selectors were not context sensitive and you were using id in prependTo which has to be unique, but you had 2 divs with the same id.
Did you mean to do this instead?
$('.product-actions').each(function() {
$elem = $("<div class='new_details_location'></div>");
$(this).find(".details").prependTo($elem);
$(this).prepend($elem);
});
$('.buttons_3').attr('class', 'buttons buttons_2 group');
http://jsfiddle.net/samliew/upKhq/4/
You can use each jquery method:
$('.product-actions').each(function() {
var self = $(this);
var new_location = $("<div id='new_details_location'></div>").prependTo(self);
self.find(".details").prependTo(new_location);
self.find('.buttons_3').attr('class','buttons buttons_2 group');
});
And you should not use the same id for two elements.
use .each, and use $(this) to refer to the current .product-actions element. Also you cant have multiple ids that are the same, only the first one would ever be used
if ($('.product-actions').length ) {
$('.product-actions').each(function() {
var newDetailLocation = $('<div></div>');
$(this).prepend(newDetailLocation);
$(".details",$(this)).prependTo(newDetailLocation);
$('.buttons_3',$(this)).attr('class','buttons buttons_2 group');
});
}

Toggle innerHTML

I've seen various examples come close to what I am looking for, but none of it seems to describe it how I exactly want it. I am a beginner to jQuery, so explanations welcome.
I'm looking for this to toggle the innerHTML from - to +. Anyone know of a way to do this, efficiently?
jQuery/JavaScript
$(document).ready(function() {
$(".A1").click(function() {
$(".P1").toggle("slow");
$(".A1").html("+");
});
});
HTML
<div class="A1">-</div>
<h2 class="H1">Stuff</h2>
<div class="P1">
Stuffy, Stuffy, Stuffed, Stuffen', Stuffing, Good Luck Stuff
</div>
Thank you, anything relating to switching the inside text of an HTML element shall help. =)
How about adding a class that will let you know the expanded/collapsed status?
$(document).ready(function() {
$(".A1").click(function() {
var $this = $(this);
$(".P1").toggle("slow")
$this.toggleClass("expanded");
if ($this.hasClass("expanded")) {
$this.html("-");
} else {
$this.html("+");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="A1 expanded">-</div>
<h2 class="H1">Stuff</h2>
<div class="P1">
Stuffy, Stuffy, Stuffed, Stuffen', Stuffing, Good Luck Stuff
</div>
Example: http://jsfiddle.net/sGxx4/
$(document).ready(function() {
$(".A1").click(function() {
$(".P1").toggle("slow");
$(".A1").html(($(".A1").html() === "+" ? $(".A1").html("-") : $(".A1").html("+")));
});
});
A bit of explanation: I'm setting $("#A1").html() with the product of the tertiary operator, using it to check for the current value of #A1's text. If it's a +, I set the element's text to -, otherwise, I set it to +.
However, you said "efficiently." To this end, it's important to note that if you're going to use a selector twice or more in the same function, you should store the jQuery object that results from the selector you give in a variable, so you don't have to re-run the selector each time. Here's the code with that modification:
$(document).ready(function() {
$(".A1").click(function() {
var $A1 = $(".A1");
$(".P1").toggle("slow");
$A1.html(($A1.html() === "+" ? $A1.html("-") : $A1.html("+")));
});
});
There's no way to toggle content.
You could check if the $('.P1') is visible, then changing the +/- div according to that.
Something like :
$(document).ready(function() {
$(".A1").click(function() {
$(".P1").toggle("slow", function(){
if($(this).is(':visible'))
$(".A1").html("-")
else
$(".A1").html("+")
});
});
});
Using a callback function (the second argument of the .toggle() method) to do the check will guarantee that you're checking after the animation is complete.
JsFiddle : http://jsfiddle.net/cy8uX/
more shorter version
$(document).ready(function() {
$(".A1").click(function() {
var $self = $(this);
$(".P1").toggle("slow", function ( ) {
$self.html( $self.html() == "-" ? "+" : "-");
});
})
});
Here's a way that uses class names on a parent and CSS rules and doesn't have to change the HTML content and works off a container and classes so you could have multiple ones of these in the same page with only this one piece of code:
HTML:
<div class="container expanded">
<div class="A1">
<span class="minus">-</span>
<span class="plus">+</span>
</div>
<h2 class="H1">Stuff</h2>
<div class="P1">
Stuffy, Stuffy, Stuffed, Stuffen', Stuffing, Good Luck Stuff
</div>
</div>​
CSS:
.expanded .plus {display:none;}
.collapsed .minus {display: none;}
Javascript:
$(document).ready(function() {
$(".A1").click(function() {
$(this).closest(".container")
.toggleClass("expanded collapsed")
.find(".P1").slideToggle("slow");
});
});
​
Working demo: http://jsfiddle.net/jfriend00/MSV4U/

Categories