Jquery .on event.trigger not refreshed on second click - javascript

Hi I'm getting trouble with one strange behavior with this:
I got a link which feeds some data attributes to another link(back link of a slider)
<div class="col-sm-4 etapes etape1 btn-back"
data-classtarget="row_containerHover"
data-currentcontainerid="row_containerHover2"></div>
and the back link code
$('body').on('click touchstart', '.btn-back', function (e) {
//$('.btn-back').on('click touchstart', function (e) {
//console.log('click btn-back');//test ok
//var container = $(e.target).closest('.slide_containerHover');
var container = $("#"+$(e.currentTarget).data('currentcontainerid'));
console.log("current container : "+container.attr("id"));
var container_class_target = $(e.target).data("classtarget");
var prev_container = $("#"+container_class_target);
console.log("prev container : "+prev_container.attr("id"));
//On récup le niveau du container ds l'arborescence
/*var level_container = container.data('level');
var prev_level = parseInt(level_container - 1);*/
//On récup le container précédent
var decalX = parseInt(parseInt($(window).outerWidth() / 2)
+ parseInt(container.outerWidth() / 2));
console.log("ledecalX : "+decalX);//test
container.animate({
left: "+=" + decalX
}, 500, 'easeInOutQuad');
//console.log('row_containerHover outerWidth : '+decalX);//test
setTimeout(function () {
prev_container.animate({
left: "0px"
}, 500, 'easeInOutQuad'), 100
});
}
First time it's ok, my data attributes are correct. When I click another link, the data attributes are changed in my html, but the console test doesn't display the changed values of $(e.currentTarget).data('currentcontainerid')
Is there a way to get the refreshed data attributes of $(e.currentTarget)?
Thanks For all

Finally I've found a way by removing it with the jquery .removeData at the end of procedure :
$(e.currentTarget).removeData('classTarget');
$(e.currentTarget).removeData('currentcontainerid');
Now it works like a charm ^_^ thanks for your Help

You are looking for dataset instead of data(). With dataset you can set and get values dinamically.
How it works?
$(selector).get(0).dataset.currentcontainerid; // returns data-currentcontainerid value
$(selector).get(0).dataset.currentcontainerid = "new value"; // set the new value
I use get(0) to return the DOM object instead the jQuery object. You can make it with pure javascript:
document.getElementById("element").dataset.currentcontainerid = "new value"; // set the new value
More information:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

Related

Reset the initial state of an element after some DOM manimulations (native js)

I want to save the initial state of my Element (with all childs) and after that do some actions ( initialize scrollbar plugin ) and after the window resize event I want to clear these changed values to the saved "pure" element and after that re-initialize the scrollbar plugin (I just want to do a scrollbar element responsive with the different views).
I tried to use .cloneNode(true), jquery.clone(true) and jquery.replaceWith() but it doesn't work for me becase these methods somehow keep all chages that was done before. So I can't get the saved initial HTML.
Should I user outerHTML maybe? Thanks for any help.
var GLOBAL_rawScrollBarNode;
var GLOBAL_scrollBarParent;
$(document).ready(function($){
GLOBAL_rawScrollBarNode = $('#scrollbar3').clone();
GLOBAL_scrollBarParent = $('.portfolio-scroll-box')[0];
portfolioScrollbarOfDeviceWidth();
$(window).resize(function(){
portfolioScrollbarOfDeviceWidth();
});
function portfolioScrollbarOfDeviceWidth() {
var documentWidth = document.documentElement.clientWidth;
//GLOBAL_scrollBarParent.removeChild(document.getElementById('scrollbar3'));
//GLOBAL_scrollBarParent.appendChild(GLOBAL_rawScrollBarNode);
GLOBAL_scrollBarParent.replaceWith(GLOBAL_rawScrollBarNode[0])
var $scrollBarEl = $('#scrollbar3');
setTimeout(() => {
if (documentWidth < 942) {
console.log("XXX")
var bar = $scrollBarEl.tinyscrollbar({ axis: 'x',sizethumb: 135 });
console.log(bar);
} else {
console.log("YYY")
var bar = $scrollBarEl.tinyscrollbar({ axis: 'y',sizethumb: 135 });
console.log(bar);
}
}, 2000)
}
P.S. in case of the outerHTML of the saved ELEMENT and after that assign it like innerHTML to it's parent - it works fine. But I want to know how this issue can be resolved in other more elegant way :)

Updating global variable on scroll event attached to a DOM element

I've got a situation where I want a variable to be updated when scrolling inside a <div>. There is a series of other things which will happen depending on this variable updating, so I don't want to wrap it inside the scroll event. Is there a way to avoid that?
Here is my JS:
var scrollEl = document.getElementById("scrollEl");
var scrollElWidth = scrollEl.offsetWidth;
var scrolled = 0;
var updater = function(updated) {
scrolled = Math.round(updated);
return scrolled;
}
scrollEl.addEventListener("scroll", function() {
var percentage = 100 * scrollEl.scrollLeft / (scrollEl.scrollWidth - scrollElWidth);
//This works
console.log(updater(percentage));
});
//This doesn't
console.log('Updated scroll variable: ', scrolled);
Here is a fiddle: https://jsfiddle.net/0u4fp0yv/

jQuery swipe with Snap svg

The following code gives the alert and shows in the console, but it doesn't call the function - why could this be?
$('.eventSliderClass').on("swipe",function(event){
infoRectClick();
console.log('swiped!');
alert("Swiped!");
});
var infoRectClick = function() {
eventSlider.attr('display', '');
eventSliderContent.animate({'transform' : 't0,0'}, 250);
};
Also is there any reason why I can't seem to retrieve the id from a var and had to create a class?

javascript event running when the mouse is over elements created by another function

This function create_canvas_card() creates a box with smaller boxes in it. How do I get it to call the function card_mouseover() whenever the mouse is over one of the boxes?
function create_canvas_card(card_data, each_card){//where card_data is an element/object and each_card is an int
click_canvas_card_x = 10, click_canvas_card_y = 10;//these are set elsewhere
image_id = $(card_data.node).data('card')
click_canvas_cards[each_card] = click_canvas.rect(click_canvas_card_x, click_canvas_card_y, 40, 40).attr('fill', 'url(/images/thumbnails/image'+ image_id +'.jpg)');
//my attempt
$(card_data.node).bind('mouseover', function(e){
var card = cards[$(this).data('card')];
card_mouseover(card);
});
//another attempt
//click_canvas_cards[each_card].mouseover(click_canvas_card_mouseover(card_data.node));
}
which is called from this loop
for(each_card in cards_to_create_for_click){
var card_data = cards_to_create_for_click[each_card];
create_canvas_card(card_data, each_card);
}
So far neither's worked.
Use Raphael's built in Element.hover() method.
Element.hover
I've made a quick little fiddle to show you it in action here
For your example, I imagine you'd want to change your function to something like this:
function create_canvas_card(card_data, each_card){
click_canvas_card_x = 10, click_canvas_card_y = 10;//these are set elsewhere
image_id = $(card_data.node).data('card')
click_canvas_cards[each_card] = click_canvas.rect(click_canvas_card_x, click_canvas_card_y, 40, 40)
.attr('fill', 'url(/images/thumbnails/image'+ image_id +'.jpg)')
.hover(function(){
//Do something on hover
});

Set onCLick callback inside object?

I have a carousel object, with images and a pager. The problem is I can't set the onClick to the pager. I'm obviously missing something here but I don't know what.
The error when I click in a pager item is:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'scrollCarouselTo'
I set my onclick
carouselDots.on('click',function(){
this.scrollCarouselTo(1,5); // <-- problem lies here, how can i call this method?
});
and the scrollTo method
this.scrollCarouselTo=function(dotIndex, numDots)
{
//H_SCROLL.scrollToElement("#carouselItem"+dotIndex, 300);
H_SCROLL.scrollToPage(dotIndex, 0 , 300);
this.highlightCarouselDot(dotIndex, numDots);
}
Last, on my HTML file this is how I set it:
var tempCarousel = new Carousel();
tempCarousel.initialize(params,cont,scrollContainer);
My Carousel class: (parts of it that i think are relevant)
function Carousel() {
var container;
var pager;
var opt;
var thisCarousel;
//render the correct number of dots and highlight the indexed one
this.highlightCarouselDot=function(dotIndex, numDots)
{
var ui_str="";
console.log("numDots" + numDots);
for (var i=0;i<numDots;i++)
{
if (i==dotIndex)
ui_str+='<div class="carouselDot selected" id="carouselDot'+i+'"></div>';
else
ui_str+='<div class="carouselDot" id="carouselDot'+i+'"></div>';
}
console.log(ui_str);
console.log(pager);
pager.html(ui_str);
var carouselDots = $(pager.selector + " .carouselDot");
var dotSelected = $(pager.selector + " .selected");
carouselDots.css('background',opt.pagerImage);
carouselDots.width(opt.pagerSize);
carouselDots.height(opt.pagerSize);
carouselDots.on('click',function(){ //replace with touch
this.scrollCarouselTo(0,5);
});
dotSelected.css('background',opt.pagerSelectedImage);
}
this.scrollCarouselTo=function(dotIndex, numDots)
{
//H_SCROLL.scrollToElement("#carouselItem"+dotIndex, 300);
H_SCROLL.scrollToPage(dotIndex, 0 , 300);
this.highlightCarouselDot(dotIndex, numDots);
}
}
Thank you!
You are having trouble understanding where the scope is changing in your code. Yes this refers to the object you are in, but when you assign an event handler such as onclick, that function is run in the scope of the UI element that was clicked. This means that in your onclick code, this refers to the html object that was clicked, and not the highlightCarouselDot object.
One common solution to this problem is to use an extra variable to store the value of this.
var self = this;
at the start of your object, that way you can refer to self within your event handlers when you want to refer to the outside object.

Categories