Changed ID not being found by jQuery
It works with the same principle as Event binding on dynamically created elements?.
When you add a event handler to an element where the element is found using a selector, the selector is executed only once when the code is executed after that the handler is added to the element. Once is has happend if you change the selector values associated with the element it will not reflect in the attached handlers.
For example in your case you are adding the a handler to the element with id before
in dom ready handler, so once the dom ready event is fired your selector is evaluated and it returns a single element to which you are adding the handler. In the same dom ready handler you are trying to add a click handler to an element with id after
, but at dom ready there are no elements with that id so that handler is not attached to any element.
Now at a later time you are changing the id of the elemnet, but it will not affect in the already attached handler nor will it add a new handler.
The solution here is to use a mechanism known as event delegation.
Demo:
$(document).ready(function() { //there is no need to use hover as your want to add the class when the mouse enter the element and you don't want to do anything in mouseleave $("#mytarget").mouseenter(function() { $(this).addClass("after").removeClass('before'); });
//look at the use of event delegation $(document).on('click', '.after', function() { alert("Handler for .click() called."); })});
.before { color: maroon;}.after { color: blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><p id="mytarget" class="before">TEST TEXT</p>
Changing the ID for an element doesn't work with jQuery
.
is for classes and #
is for ids, plus you have to use the .on()
function, otherwise it will not work
$(document).on('click','#pre_div',function() {
$(this).attr('id','after_div');
});
$(document).on('click','#after_div',function() {
$(this).attr('id','pre_div');
});
JSFIDDLE DEMO
Jquery change id, not working
$(document).ready(function(){
var id = "original";
var row = "some_row";
var col = "some_col"
var treasure_list = [];
var grav_treasure_tree = function(id, row){
// some code
}
var rand_id=Math.floor(Math.random()*100);
var new_id = "treasure_grass_"+row+"_"+rand_id;
new_id = new_id + "_col_" + col;
treasure_list.push(new_id);
if($("#"+id).length > 0){
alert(new_id);
$("#"+id).attr("id",new_id);
grav_treasure_tree(id, row);
}
});
That works if I have a div with id original
:
<div id="original">
</div>
jQuery: Changing div ID not working
</img>
tag is not a valid tag cause images don't have a closing tag.
Also, jQuery is much more fun that you might think!
My suggestion is to not create <img>
tags at all, let JavaScript do it for us, we're using an Array of images URL, after all.
Instead of jQuery's .animate()
, use CSS transition
!
jQuery(function($) {
const gallery = { one: [ // (P.S: In HTML use data-gallery="one") 'http://placehold.it/900x400/0bf/fff&text=1', 'http://placehold.it/900x400/f0b/fff&text=2', 'http://placehold.it/900x400/bf0/fff&text=3', 'http://placehold.it/900x400/b0f/fff&text=4', ], // you can add more name:[] sets for other galleries };
$('[data-gallery]').each(function(i, gal) { const name = $(gal).data('gallery'); if (!Object.prototype.hasOwnProperty.call(gallery, name)) return; const $slides = $(gallery[name].map(url => $('<img>', {src: url})[0])); const tot = $slides.length; // Store how many images we have let c = 0; // Current slide Counter
$('.slides', gal).append($slides); // Append created slides $(".prev, .next", gal).on('click', function() { c = ($(this).is('.next') ? ++c : --c) < 0 ? tot - 1 : c % tot; $slides.css({ transform: `translateX(-${c*100}%)` }) });
});
});
/*QuickReset*/*{margin:0;box-sizing:border-box}html,body{min-height:100%;font:14px/1.4 sans-serif;}
/* Gallery */
[data-gallery] .slides { display: flex; position: relative; overflow: hidden; height: 170px;}
[data-gallery] .slides > img { width: 100%; height: 100%; object-fit: cover; transition: 0.4s;}
<div data-gallery="one" class="gallery"> <div class="slides"></div> <button class="prev" type="button">PREV</button> <button class="next" type="button">NEXT</button></div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
jQuery changed ID won't run function
You need to use event delegation -- your click
handlers are bound to the matching elements at the time the code is first run, and only then. Since there's no #Red
element at that point in time, that second click handler isn't bound to anything.
$(document).on('click',"#Blue", function(){
$("#Blue").attr("id","Red");
});
$(document).on('click',"#Red", function(){
$("#Red").attr("id","Blue");
});
http://jsfiddle.net/mblase75/HDFyn/
http://api.jquery.com/on
That said, the "proper" way to do this would be to add and remove a class, not change the ID:
$('#btn').on('click', function(){
$(this).toggleClass("red blue");
});
http://jsfiddle.net/mblase75/mKMW6/
changing element id with jQuery not work for my function
So there are a couple of parts to my answer, bear with me:
(1) The reason it isn't working right now is because when you run $("#hide").click(function() { ...
, there aren't yet any elements on the page with the hide
id, so the function doesn't get set to run anywhere. One method you can use to get around this is to do the following:
$(".hiddendiv").on('click', '#hide', function() {
...
});
By attaching the click event handler instead to the parent div, whenever the parent sees that the event occurred in a child div with the id of hide
, it will run the function on that child div.
(2) You shouldn't be using IDs here. If at some point you have more than one button that needs this functionality on you're page, you'll be in trouble, since an ID should only be used once per page. A class would work much better in this scenario. Then you can do something like:
$(".hiddendiv").on('click','.show', function () {
$(".hiddendiv").animate({
top: "-=250"
}, "slow");
$(".show").addClass('hide').removeClass('show');
});
(3) Finally, it works! But, if we add another hiddendiv to the page, we find that when we click one, it updates all of them. We can fix that by using this
. When the function is triggered, the this
keyword will refer to the element that you clicked (either with the show
or hide
class. We can take advantage of that and do the following:
$(".hiddendiv").on('click','.show', function () {
$(this).parent().animate({
top: "-=250"
}, "slow");
$(this).addClass('hide').removeClass('show');
});
$(".hiddendiv").on('click','.hide', function () {
$(this).parent().animate({
top: "+=250"
}, "slow");
$(this).addClass('show').removeClass('hide');
});
Change element ID, but jQuery still fires event calling old ID. Why does this work?
When you do this:
$("#block").hover(function() {
$(this).css("backgroundColor", "red");
}, function() {
$(this).css("backgroundColor", "#888");
});
you're telling jQuery to look for the element with the block
ID and bind the hover event to it. Once this is done, the event will remain bound to that element, no matter what happens to its ID afterwards.
That is, unless you have some code that unbinds it, of course.
Related Topics
Set a Callback Function to a New Window in JavaScript
Open Url in New Tab or Reuse Existing One Whenever Possible
HTML Mobile -Forcing the Soft Keyboard to Hide
Target='_Blank' to Show in New Window, Not New Tab, Possible
Fix First Column of a Bootstrap Table
Using JavaScript to Increment Top/Left/Bottom/Right Values
Interrupting/Stop a CSS3 Transition on the Actual Position/State
Filling Empty Cells in CSS Grid Layout
Confusion About Node.Js Internal Asynchronous I/O Mechanism
How to Remove "Disabled" Attribute Using Jquery
Rendering Raw HTML with Reactjs
How to Display All Methods of an Object
Move the Mouse Pointer to a Specific Position
Wait 5 Seconds Before Executing Next Line
Event When User Stops Scrolling