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
Related
I have this while loop in PHP
<?php
while ($row = mysqli_fetch_assoc($getPosts)) {
$post_id = $row['post_id'];
echo "<td><a rel='$post_id' id='get_post_id'
onclick='active_del_modal()'>Delete</a></td>";
}
?>
In this loop, when we click on the "delete" link, the value of variable "$post_id" changes. I want to get the value of "$post_id" when it changes. I tried with this JS code
function active_del_modal() {
var x = document.getElementById("get_post_id").getAttribute("rel");
alert(x);
}
But it only gives me the last value of "$post_id". I want to get each value of "$post_id" when it changes and this value should be individual, not like this 23 46 545 545, etc. I don't want to use any framework like jQuery.
An ID must be unique in a document. So stop using static IDs in a loop.
Links go somewhere. Don't use a link if you aren't navigating. Use a button if you want something to click on to trigger JS. Apply CSS if you don't like the default appearance of a button.
A post ID is not a type of relationship. Don't abuse rel attributes. (Appropriate use would be something like <a href="page2.html" rel="next">) Use a data-* attribute if you need to associate custom data with an element.
Intrinsic event attributes have a bunch of gotchas associated with them. Don't use them. Use addEventListener and friends instead.
function active_del_modal(event) {
const button = event.target;
const id = button.dataset.postId;
console.log({
id
});
}
document.querySelector("#delete-buttons").addEventListener("click", active_del_modal);
button {
border: none;
background: none;
colour: blue;
cursor: pointer;
}
button:hover {
text-decoration: underline;
}
<ul id="delete-buttons">
<li><button type="button" data-post-id="$post_id">Delete</button></li>
<li><button type="button" data-post-id="foo">Delete</button></li>
<li><button type="button" data-post-id="bar">Delete</button></li>
</ul>
Method 1 - minimum change
onclick='active_del_modal(this)'
and you can use
function active_del_modal(link) {
var x = link.getAttribute("rel");
alert(x);
}
Method 2 - better:
window.addEventListener("load",function() {
document.querySeletor("table").addEventListener("click",function(e) {
const tgt = e.target, rel = tgt.getAttribute("rel");
if (rel) alert(rel);
})
})
I recommend using data-attributes instead of rel:
If you change id to class, you can do this
window.addEventListener("load",function() {
document.querySeletor("table").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("get_post_id")) {
const id = tgt.dataset.id;
console.log(id);
}
})
})
using
echo "<td><a data-id='$post_id' class='get_post_id'>Delete</a></td>";
LASTLY if the link is supposed to delete the row, you can do
window.addEventListener("load",function() {
document.querySeletor("table").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("delete")) {
tgt.closest("tr").remove();
}
})
})
using
echo "<td><button type="button" class='delete'>Delete</button></td>";
My Solution (EDIT : 2015-12-08) :
// FIRST WE GET THE PARENT ELEMENT
var parentEstim = document.getElementById("onglet_estim");
// MAKE A TABLE OF HIS CHILD
var enfantsEstim = parentEstim.childNodes;
// KNOW HOW MANY CHILDREN THE PARENT ELEMENT HAVE WITH .length
var Nbenfants = enfantsEstim.length;
....
for (var i = 0; i <= Nbenfants; i++) {
// IF THE CHILD ELEMENT [i] IS A HTML ELEMENT
if (enfantsEstim[i].nodeType === 1) {
enfantsEstim[i].lastChild.data = ''; // REMOVE LAST TEXT NODE
enfantsEstim[i].classList.remove('isActive');
}
document.getElementById('onglet_estim').style.width = '220px';
ClickedElement.className = 'isActive';
// ADD NEW VALUE IN THE LAST TEXT NODE FOR THE CLICKED ELEMENT
ClickedElement.lastChild.data = ' Gares';
}
DEMO : http://codepen.io/Zedash/details/pjMEMY
The Problem :
I have a little problem, I want to change the last textual node child value of a link <a> element.
For exemple, for the first link, we see the word "Saisie" wrote in it and I want to remove the text in this element if the user click on an other link and add a right text for the clicked element.
function changeInputAdresse(ClassName) {
if (ClassName.className !== 'isActive') {
ClassName.className = 'isActive';
switch(ClassName.id) {
case 'linkGares' :
ClassName.insertAdjacentHTML('beforeEnd',' Gares');
ClassName.previousElementSibling.classList.remove('isActive');
ClassName.nextElementSibling.classList.remove('isActive');
ClassName.previousElementSibling.insertAdjacentHTML('beforeEnd','');
ClassName.nextElementSibling.insertAdjacentHTML('beforeEnd','');
break;
}
}
};
// THE CODE IS NOT FINISHED OF COURSE !
a {
text-decoration:none;
color:#000;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<a id="linkSaisie" class="isActive" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-map-marker"></i> Adresse</a>
<a id="linkGares" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-train"></i></a>
<a id="linkAeroports" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-plane"></i></a>
<a id="linkLoisirs" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-fort-awesome"></i></a>
<!--THE PART OF CODE WHERE I HAVE SOME PROBLEMS-->
Thanks for your ansewers ! :)
I don't quite get what you exactly would like, but to target and change the element after an italic I would use this jQuery and vanilla JS combination:
$("#myLink").find(">i").get(0).nextSibling.nodeValue = "Changed text";
DEMO: http://jsfiddle.net/u9jq2bvy/
IIRC there is no jQuery method to target a text node, so you need some native JS.
Please let me know if I misunderstood the question and I'm gonna delete my answer.
UPDATE
Based on the comment here is a possible solution.
$(document).on("click", ".myLink", function() {
// clear all texts
$(this).parent().find("a>span").text("");
$(this).addClass("active");
$(this).children("span").text("Active text");
});
DEMO http://jsfiddle.net/u9jq2bvy/1
And here is a modified version which simply shows/hides the spans.
DEMO http://jsfiddle.net/u9jq2bvy/3/
You can use jQuery siblings
changeInputAdresse(element){
element = $(element)
if(!element.hasClass('isActive')){
element.addClass('isActive');
element.siblings().removeClass('isActive');
element.text(element.attr('id').replace('link','')) //if that's the way you get value
element.siblings().text('')
}
}
I´m doing like this. Works fine with just one div with a static name.
Problem is when i want to refresh DIV´s with other names like myDiv1, myDiv2 etc.
I have tried javascript by sending ID to the funciton, my webpage jumps up to the begining, I dont want that to happen. That doesn't happen with the code below.
$(function() {
$("#refresh").click(function(evt) {
$("#myDiv").load("update.php")
evt.preventDefault();
})
})
<div id = 'myDiv" . $row["id"]. "' ><a href='#' id='refresh'> Click Here </a></div>
This Would also work, but then I have to generate one jquery-function for every DIV
$(function() {
$("#refresh1").click(function(evt) {
$("#myDiv1").load("update.php")
evt.preventDefault();
})
})
<div id = "myDiv1" ><a href='#' id='refresh1'> Click Here 1 </a></div>
$(function() {
$("#refresh2").click(function(evt) {
$("#myDiv2").load("update.php")
evt.preventDefault();
})
})
<div id = "myDiv2" ><a href='#' id='refresh2'> Click Here 2 </a></div>
You can access the parent element in the click event and execute the load on it like this:
$(this).parent().load("update.php");
If you don't want a redirection to happen, I would suggest that you don't use a link. Maybe a button or a span
You may selects elements by beginning part of your id:
$('div[id ^= "myDiv"]')
I'm aware that this issue was addressed many times, that's why I read most of the topics on this problem that were already opened on Stack Overflow but none of the suggestions have helped me.
I have a list of div elements, each containing a hyperlink and a span element with additional information. The span elements are initially hidden and they need to be toggled whenever the sibling anchor element is clicked.
<div class="politician">
<a href="">
Антонијо Милошоски
</a>
<span class="additional" style="display: none">
2013ВМРО-ДПМНЕ1997-1
</span>
</div>
<div class="politician">
<a href="">
Силвана Бонева
</a>
<span class="additional" style="display: none">
2013ВМРО-ДПМНЕ1991-1
</span>
</div>
Here's the jQuery code I have written to handle the toggling of the hidden elements:
$('.politician a').click(function (e) {
e.preventDefault();
var $this = $(this).parent().find('span');
$(".politician span").not($this).hide();
$this.toggle();
});
My problem was already stated in the title. I'm expecting the hidden elements to be shown, but instead the page gets refreshed. I guess there has to be something wrong with the way I'm using the preventDefault() method.
EDIT
Here is the piece of code that generates the div.politician elements.
function populateList(politicians) {
var politlist = $("#list").html("");
for (var i in politicians) {
var person = politicians[i];
var politinfo = "<div class=\"politician\">" + person.name + " " + person.surname + "<span class=\"additional\" style=\"display: none\">" + person.lastserved;
for (var j in person.member)
{
var membership = person.member[j]
politinfo += membership.party + membership.enrol + membership.leave;
}
politinfo += "</span></div>";
$(politinfo).appendTo(politlist);
}
}
Since you're adding elements dynamically, you need to use event delegation:
$('#list').on('click', '.politician a', function(e) {
// your code
});
This is happending because your html is not loaded when you add click event listener to it.
Wrap your code in document.ready function, like this:
$(function(){
$('.politician a').click(function (e) {
var $this = $(this).parent().find('span');
$(".politician span").not($this).hide();
$(this).toggle();
e.preventDefault();
});
});
http://plnkr.co/edit/gist:1986619?p=preview
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/