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/
Related
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', '');
});
});
I am trying to remove the style of my a href background. The issue is when I concatenate dynamic id with selector then it don't work. But when I use complete name of selector, then it works.
I know you can mark my question as duplicate like here but they are not working for me. Please correct me.
What Works:
$("a").click(function(event)
{
var id = event.target.id;
$('#chatIdStyle4').removeAttr("style");
});
What Didn't:
$("a").click(function(event)
{
var id = event.target.id;
$('#chatIdStyle'+id).removeAttr("style");
});
OR
$("a").click(function(event) {
//alert(event.target.id);
var iddds = event.target.id;
$('#chatIdStyle["'+ iddds + '"]').removeAttr("style");
});
NOTE: var id contains the dynamic id of event fired.
EDIT as asked:
Below is my HTML+PHP code. So, what it does is actually creates 4 dynamic a href with dynamic id. What I
want is when a specific a href gets clicked then it should remove previous a href background and
add background to the clicked a href.
<?php
$color = false;
$PID = 4;
for($i=0;$i<4;$i++)
{
?>
<a <?php if($color==true)
{
?> style="background-color: #E6E6E6;" <?php
}
$color=false;
?>
id="chatIdStyle<?php echo $PID; ?>"
href="#">
</a>
<?php
}
?>
I suggest using CSS solution instead of jQuery:
a { background: none; }
a:active { background: #E6E6E6; }
The second line will set the background for the last clicked a element.
About the :active pseudo class: https://www.w3schools.com/cssref/sel_active.asp
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 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 want change part two of class name in each div into tag <span> from '.myclass_2' to 'yourclass', (in following html code). Here is my try with jQuery but they doesn't work true. How is fix it?
Demo: http://jsfiddle.net/sTF3U/
<span>
<div class="myclass_1 myclass_2">
Click Me_1
</div>
<div class="myclass_1 myclass_2">
Click Me_2
</div>
</span>
var $this = $('.click'),
$clone_1 = $('span').clone();
alert($clone_1.html());
$('.click').live('click', function (e) {
e.preventDefault();
$clone_2 = $('span').clone();
$clone_2.find('div').split(" ")[1].addClass('youClass');
$clone.find('.auto_box2:last .mediumCell').each(function () {
$(this).split(" ")[1].removeClass().addClass(unique());
});
var $result = $('span').clone();
alert('ok');
})
Try this:
$("div.myclass_2").removeClass("myclass_2").addClass("yourclass");
BTW, a <div> inside a <span> is not valid HTML.
Juse use removeClass passing the required class to remove and then use addClass passing the required class to add to any element. Try this
$(".myclass_2").removeClass("myclass_2").addClass("yourclass");
Use jquery removeClass and addClass method to remove the existing class and then add the renamed class