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', '');
});
});
Related
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>
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>
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');
});
}
I'm searching hours for an solution and found some answers, but not a quite fitting one.
I have several <span id="same-id-for-all-spans"></span> elements with each of them including one <img> element.
Now I want to create a print template, to only print those elements which have a specific class added to it.
The question is, how can I add a class to a span by clicking on it.
This way I want to "mark" several spans which then have an underlying print-css style to only print the ones with the specific*class*.
Important: It should be possible to click (add class) and reclick (delete class) for single spans.
Thank you so much.
Best Regards
Mazey
its a wordpress return for all the spans, so same id.
at the moment I have this js included:
<script type="text/javascript">
function changeid ()
{
var e = document.getElementById("nonprintable");
e.id = "printable";
}
</script>
and the wordpress code looks like this:
<?php
$args = array('post_type' => 'attachment', 'post_parent' => $post->ID, 'orderby' => 'menu_order', 'order' => 'ASC');
$attachments = get_children($args);
foreach ( $attachments as $attachment_id => $attachment ) {
echo '<span id="nonprintable" onClick="changeid()" >';
echo wp_get_attachment_image( $attachment->ID, 'large' );
echo '</span>';
}
?>
Right now when I click on a span I see that it changes the id. But it changes it just top to bottom with every click on a span and not on a specific span I click.
you can use
jQuery('span').click(function(){
jQuery(this).toggleClass('yourSpecialClass');
});
First of all, you should not have the same id for all your spans. Instead add a class to all of them like this:
<span class="selectable"></span>
Then you can do this:
$(function(){
$(".selectable").click(function(){
$(this).toggleClass("selected");
});
});
And then in your function
function getAllSelected(){
var selected = $(".selected"); // This will give you all the selected elements.
}
could use the following
$("span").click(function() {
if($(this).hasClass("classname"))
{
$(this).removeClass("classname");
}
else
{
$(this).addClass("classname");
}
});
Add an onclick handler and toggle CSS classes:
JS:
function addClass(obj) {
obj.className ? obj.className = "" : obj.className = "test";
}
CSS:
.test {
color: red;
}
HTML Span:
<span onclick="addClass(this)">Click me!</span>
Demo: http://jsfiddle.net/yXWcW/1/
Edit: Didn't see the jQuery tag, use toggleClass for that.
<div class="items">
<span class="item">Click Item 1</span>
<span class="item">Click Item 2</span>
<span class="item">Click Item 3</span>
</div>
<div class="btn-getSelectedItems">Get Selected Items</div>
$(function(){
$('.items .item').click(function(){
$(this).toggleClass('selected');
})
$('.btn-getSelectedItems').click(function(){
if($('.items .selected').length){
console.log($('.items .selected'))
}
})
})
You can do this
<span id="nonprintable" onClick="changeid(this)" >
added "this" to arguments
and your function would be
<script type="text/javascript">
function changeid (e){//added e to accepted arguments
e.id = "printable";
//e is the element so you are only changing that one elements id
}
</script>
or you can just use jQuery's .toggleClass
<span onclick="$(this).toggleClass('your-classname');">Click me!</span>
Since you have multiple instances (I would recomend classes instead of id's)
$('#same-id-for-all-spans').click(function(){
$(this).toggleClass('your-classname');
});
Here is the jQuery doc for .toggleClass()
http://api.jquery.com/toggleClass/
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/