I'm having problems with firing of a function whenever my ID is clicked. Currently, this is how my code looks:
$(document).ready(function () {
if (self != top) {
top.location.replace(location.href);
}
$(document).mousedown(function (e) {
if (e.button == 2) {
console.log('mousdown');
$(window).blur();
}
});
$(document).mouseup(function (e) {
if (e.button == 2) {
console.log('mousup');
$(window).blur();
}
});
var $iframe_height = $(window).innerHeight() - 90;
$('iframe').attr('height', $iframe_height + 'px');
$(window).resize(function () {
var $iframe_height = $(window).innerHeight() - 90;
$('iframe').attr('height', $iframe_height + 'px');
});
$('.message').html('<div class="alert alert-warning">Waiting for advertisement to load...</div>');
$('.close').on('click', function () {
window.open('', '_self', '');
window.close();
});
var $seconds = 5;
var $window_width = $(window).innerWidth();
var $width_per_second = $window_width / $seconds;
var $timer = null,
$current_second = 0;
setTimeout(function () {
if ((!$('body').hasClass('done')) && (!$('body').hasClass('blocked')) && (!$('body').hasClass('ready'))) {
$('body').addClass('ready');
$('.message').html('<div class="alert alert-info">Click <b id="start" style="cursor:pointer;text-decoration:underline;">here</b> to start viewing this advertisement.</div>');
}
}, 3000);
document.getElementById("website").onload = function () {
if ((!$('body').hasClass('done')) && (!$('body').hasClass('blocked')) && (!$('body').hasClass('ready'))) {
$('body').addClass('ready');
$('.message').html('<div class="alert alert-info">Click <b id="start" style="cursor:pointer;text-decoration:underline;">here</b> to start viewing this advertisement.</div>');
}
};
$("#start").click(function () {
$('#website').focus();
$('.message').html('<div class="alert alert-info"><b id="seconds">' + parseFloat($seconds - $current_second) + '</b> seconds remaining (do not leave this page).</div>');
if ($timer !== null) return;
$timer = setInterval(function () {
if ($current_second == $seconds) {
clearInterval($timer);
$('.message').html('<div class="alert alert-success">Checking if you won, please wait…</div>');
var $id = 10977;
var $reffbux_fp = new Fingerprint();
var $reffbux_fp = $reffbux_fp.get();
$.ajax({
url: 'http://reffbux.com/account/register_roulette',
type: 'post',
data: {
id: $id,
fp: $reffbux_fp
},
success: function (result, status) {
$('html, body').animate({
scrollTop: 0
}, 500);
$('body').addClass('done');
$('.melding').fadeOut(0).fadeIn(500);
$('.message').html(result);
$('.counter_bar').addClass('done');
}
});
return false;
} else {
var $counter_bar_width = $('.counter_bar').innerWidth();
$('.counter_bar').css('width', parseFloat($counter_bar_width + $width_per_second).toFixed(2));
$current_second++;
$("#seconds").text(parseFloat($seconds - $current_second));
}
}, 1000);
});
$('body').mouseleave(function () {
if ((!$(this).hasClass('done')) && (!$(this).hasClass('blocked')) && ($(this).hasClass('ready'))) {
$('.message').html('<div class="alert alert-error">You navigated away from the advertisement. Click <b id="start" style="cursor:pointer;text-decoration:underline;">here</b> to resume.</div>');
clearInterval($timer);
$timer = null
}
});
});
A text with id="start" will be generated when the iframes content is loaded. The problem is, whenever I click on the id="start" nothing happens. Nothing. The console log doesn't report any error before I click nor does it report any error after I've clicked.
I can't seem to find what the problem is.
You have to use the jquery on to bind events to dynamically created elements.
$('.message').on('click', '#start', function(){
Where .message is the elelment your #start element is in.
Related
I'm creating product variant accordions for my Shopify store and so far I've been able to make it so that the accordions will open but they won't collapse when you click on them again. If anyone can provide some guidance on what I'm doing wrong I'd appreciate it!
function swatchNamePlacement() {
$('.swatches .swatch-view .swatch-img-text').each(function () {
var elm = $(this);
var parent = elm.closest('.swatch-view-item');
parent.append(elm);
});
}
function isSwatchKingLoaded() {
var watch = setInterval(myTimer, 200);
function stopTimer() {
clearInterval(watch);
}
function myTimer() {
if(typeof VariantSwatchKing !== "undefined" && VariantSwatchKing !== '') {
if($('.swatches').length > 0){
$('.swatches > div').eq().addClass('open');
stopTimer();
swatchNamePlacement();
}
}
}
}
$('.product__info-wrapper').on('click','.swatches > div', function(e){
e.preventDefault();
var element = $(this);
var parent = element.parent();
// parent.toggleClass('open');
if(parent.hasClass('open')) {
element.removeClass('open')
} else {
parent.find('.swatches > div').removeClass('open');
element.addClass('open')
}
});
So I have a MVC code that generates something like this
<div class="photoset">
<img />
<img />
</div>
<div class="photoset">
<img />
<img />
<img />
</div>
And I'm trying to make a jQuery to infinite scroll and as the user is scrolling, it generates more photosets.
I was somewhat successful in doing that but, after I generate more photosets with my infinite scroll, the newly added code won't work with my previous jQuery plugin to navigate between images.
Here is the jQuery code to navigate:
jQuery
$(document).ready(function () {
$('.photoset').each(function () {
$(this).data('counter', 0);
$items = $(this).find('img')
$(this).data('numItems', $items.length);
$(this).closest('.row').prev('.row').find('.nav-informer').text($(this).data('counter') + 1 + " de " + $(this).data('numItems'));
if (($items.eq(0).width() / $items.eq(0).height()) < 1) {
$(this).css({
width: "445",
height: "667",
margin: "auto"
});
}
});
var showCurrent = function (photoset) {
$items = photoset.find('img');
var counter = photoset.data('counter');
var numItems = $items.length;
var itemToShow = Math.abs(counter % numItems);
$items.fadeOut(1000);
$items.eq(itemToShow).fadeIn(1000);
};
/* ---------------------------------------------- /*
* Prev
/* ---------------------------------------------- */
$('.prev').on('click', function () {
var photoset = $(this).closest('.row').prev('.row').find('.photoset');
photoset.data('counter', photoset.data('counter') - 1);
if (photoset.data('counter') < 0)
photoset.data('counter', photoset.data('numItems') - 1);
photoset.closest('.row').prev('.row').find('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));
showCurrent(photoset);
});
/* ---------------------------------------------- /*
* Next
/* ---------------------------------------------- */
$('.next').on('click', function () {
var photoset = $(this).closest('.row').prev('.row').find('.photoset');
photoset.data('counter', photoset.data('counter') + 1);
if (photoset.data('counter') > photoset.data('numItems') - 1)
photoset.data('counter', 0);
photoset.closest('.row').prev('.row').find('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));
showCurrent(photoset);
});
});
And the Ajax function to call for more photosets, passing the page number:
Ajax
var page = 0,
inCallback = false,
hasReachedEndOfInfiniteScroll = false;
var ulScrollHandler = function () {
if (hasReachedEndOfInfiniteScroll == false &&
($(window).scrollTop() == $(document).height() - $(window).height())) {
loadMoreToInfiniteScrollUl(moreRowsUrl);
resizeNewElements();
}
}
function loadMoreToInfiniteScrollUl(loadMoreRowsUrl) {
if (page > -1 && !inCallback) {
inCallback = true;
page++;
$(".loading").show();
$.ajax({
type: 'GET',
url: loadMoreRowsUrl,
data: "pageNum=" + page,
success: function (data, textstatus) {
if (data != '') {
$(".infinite-scroll").append(data);
}
else {
page = -1;
}
inCallback = false;
$(".loading").hide();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
}
}
function showNoMoreRecords() {
hasReachedEndOfInfiniteScroll = true;
}
And this is the function that calls the infinite scroll:
$(function () {
$(".loading").hide();
});
var moreRowsUrl = '#Url.Action("index", "home")';
$(window).scroll(ulScrollHandler);
I did some research but couldn't stabilish a reason why my code doesn't work, tried some things but did not have success. If anyone could help me, would be great! Thanks in advance, and sorry for any mistake, I'm extremely new with jQuery and Ajax.
You can try with the event delegation for the click event on .prev and .next elements:
$(document).ready(function(){
$(document).on('click', '.prev', function(){.....});
$(document).on('click', '.next', function(){.....});
});
I have two "stopwatches" in my code (and I may be adding more). This is the code I currently use below - and it works fine. But I'd really like to put the bulk of that code into a function so I'm not repeating the same code over and over.
When I tried doing it though, I could get it working - I think it was because I was passing stopwatchTimerId and stopwatch2TimerId into the function and it may have been passing by reference?
How can I reduce the amount of code repetition here?
var stopwatchTimerId = 0;
var stopwatch2TimerId = 0;
$('#stopwatch').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
$(this).addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch-seconds').val()) || 0;
$('#stopwatch-seconds').val(currentValue + 1).change();
}, 1000);
}
});
$('#stopwatch2').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatch2TimerId);
}
else {
$(this).addClass('active');
stopwatch2TimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch2-seconds').val()) || 0;
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
});
As you can see, it's basically the same code in each except for stopwatchTimerId and $('#stopwatch-seconds') (and the same vars with 2 on it for the other one).
This won't pollute global scope and also you don't need to do any if-else statements. Just add data-selector to your new elements :)
<input id="stopwatch" type="text" data-selector="#stopwatch-seconds"/>
<input id="stopwatch2" type"text" data-selector="#stopwatch2-seconds"/>
$('#stopwatch stopwatch2').click(function () {
var $element = $(this),
interval = $element.data('interval');
selector = $element.data('selector');;
if ($element.hasClass('active')) {
$element.removeClass('active');
if (interval) {
clearInterval(interval);
}
}
else {
$element.addClass('active');
$element.data('interval', setInterval(function () {
var currentValue = parseInt($(selector).val()) || 0;
$(selector).val(currentValue + 1).change();
}, 1000));
}
});
function stopwatch(id){
$('#' + id).click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(window[id]);
}
else {
$(this).addClass('active');
window[id] = setInterval(function () {
var currentValue = parseInt($('#' + id + '-seconds').val()) || 0;
$('#' + id + '-seconds').val(currentValue + 1).change();
}, 1000);
}
});
}
$(function(){
stopwatch("stopwatch");
stopwatch("stopwatch2");
});
You could do something like this (code is not very nice, you can improve it):
var stopwatchTimerId;
$('#stopwatch').click(function () {
doStopWatch(1);
});
$('#stopwatch2').click(function () {
doStopWatch(2);
});
var doStopWatch = function(option){
var stopWatch = option===1?$('#stopwatch'):$('#stopwatch2');
if (stopWatch.hasClass('active')) {
stopWatch.removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
stopWatch.addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = option===1?(parseInt($('#stopwatch-seconds').val()) || 0):(parseInt($('#stopwatch2-seconds').val()) || 0);
if(option===1)
$('#stopwatch-seconds').val(currentValue + 1).change();
else
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
}
Try
var arr = $.map($("div[id^=stopwatch]"), function(el, index) {
el.onclick = watch;
return 0
});
function watch(e) {
var id = this.id;
var n = Number(id.split(/-/)[1]);
if ($(this).hasClass("active")) {
$(this).removeClass("active");
clearInterval(arr[n]);
} else {
$(this).addClass("active");
arr[n] = setInterval(function() {
var currentValue = parseInt($("#" + id + "-seconds").val()) || 0;
$("#" + id + "-seconds").val(currentValue + 1).change();
}, 1000);
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="stopwatch-0">stopwatch1</div>
<input type="text" id="stopwatch-0-seconds" />
<div id="stopwatch-1">stopwatch2</div>
<input type="text" id="stopwatch-1-seconds" />
I create a pop-up dialog box which lift up on left bottom while user scroll page.
You can see it live here- http://uposonghar.com/jobs/odesk/daniel/new/
My problem is it does not smoothly lift up first time, then it is ok. Anyone please suggest any idea to fix it. Need to make smoothly lift up.
My code
<div id="scrolltriggered" style="width: 310px; left: 10px; bottom: 10px;">
<div id="inscroll">
x<a href="http://www.google.com" target="_blank"><img src="images/buyersguide.png" alt="Free Resources" height="235" width="310">
</a>
</div>
</div>
<script type="text/javascript">
var stb = {
hascolsed: false,
cookieLife: 7,
triggerHeight: 30,
stbElement: ""
};
</script>
Javascript Code-
if (typeof stb === "undefined")
var stb = {};
jQuery(document).ready(function () {
jQuery("#closebox").click(function () {
jQuery('#scrolltriggered').stop(true, true).animate({ 'bottom':'-210px' }, 700, function () {
jQuery('#scrolltriggered').hide();
stb.hascolsed = true;
jQuery.cookie('nopopup', 'true', { expires: stb.cookieLife, path: '/' });
});
return false;
});
stb.windowheight = jQuery(window).height();
stb.totalheight = jQuery(document).height();
stb.boxOffset = '';
if (stb.stbElement != '') {
stb.boxOffset = jQuery(stb.stbElement).offset().top;
}
jQuery(window).resize(function () {
stb.windowheight = jQuery(window).height();
stb.totalheight = jQuery(document).height();
});
jQuery(window).scroll(function () {
stb.y = jQuery(window).scrollTop();
stb.boxHeight = jQuery('#scrolltriggered').outerHeight();
stb.scrolled = parseInt((stb.y + stb.windowheight) / stb.totalheight * 100);
if (stb.showBox(stb.scrolled, stb.triggerHeight, stb.y) && jQuery('#scrolltriggered').is(":hidden") && stb.hascolsed != true) {
jQuery('#scrolltriggered').show();
jQuery('#scrolltriggered').stop(true, true).animate({ 'bottom':'10px' }, 700, function () {
});
}
else if (!stb.showBox(stb.scrolled, stb.triggerHeight, stb.y) && jQuery('#scrolltriggered').is(":visible") && jQuery('#scrolltriggered:animated').length < 1) {
jQuery('#scrolltriggered').stop(true, true).animate({ 'bottom':-stb.boxHeight }, 700, function () {
jQuery('#scrolltriggered').hide();
});
}
});
jQuery('#stbContactForm').submit(function (e) {
e.preventDefault();
stb.data = jQuery('#stbContactForm').serialize();
jQuery.ajax({
url:stbAjax.ajaxurl,
data:{
action:'stb_form_process',
stbNonce:stbAjax.stbNonce,
data:stb.data
},
dataType:'html',
type:'post'
}).done(function (data) {
jQuery('#stbMsgArea').html(data).show('fast');
});
return false;
});
});
(function(stb_helpers) {
stb_helpers.showBox = function(scrolled, triggerHeight, y) {
if (stb.isMobile()) return false;
if (stb.stbElement == '') {
if (scrolled >= triggerHeight) {
return true;
}
}
else {
if (stb.boxOffset < (stb.windowheight + y)) {
return true;
}
}
return false;
};
stb_helpers.isMobile = function(){
if (navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
) {
return true;
}
else return false;
}
})(stb);
i think you need css changes, copy paste the following in your aspx
<div style="width: 310px; left: 10px; bottom: -225px; display: none;" id="scrolltriggered">
Hope it Helps
All you need to do is add the following line to your document ready as the First line
$("#scrolltriggered").css({bottom: -235});
This will make sure that the popup is scrolled to the bottom by 235px. If you need it to scroll variably add the Elements height by using jquery selector.
See the Fiddle Here
I Have find a javascript code that works perfectly for showing a DIV.
but this code works only for showing one div for each page.
i want to include many DIVS for hiding and showing in the same page.
I was try to replace the div id and show/hide span id with a rundom php number for each include, but still is not working.
so how i have to do it?
the JS code:
var done = true,
fading_div = document.getElementById('fading_div'),
fade_in_button = document.getElementById('fade_in'),
fade_out_button = document.getElementById('fade_out');
function function_opacity(opacity_value) {
fading_div.style.opacity = opacity_value / 100;
fading_div.style.filter = 'alpha(opacity=' + opacity_value + ')';
}
function function_fade_out(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'none';
done = true;
}
}
function function_fade_in(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'block';
}
if (opacity_value == 100) {
done = true;
}
}
// fade in button
fade_in_button.onclick = function () {
if (done && fading_div.style.opacity !== '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_in(x)
};
})(i), i * 10);
}
}
};
// fade out button
fade_out_button.onclick = function () {
if (done && fading_div.style.opacity !== '0') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_out(x)
};
})(100 - i), i * 10);
}
}
};
Check out the Fiddle, you can edit code based on your needs ;)
$(function() {
$('.sub-nav li a').each(function() {
$(this).click(function() {
var category = $(this).data('cat');
$('.'+category).addClass('active').siblings('div').removeClass('active');
});
});
});
finaly i found my self:
<a class="showhide">AAA</a>
<div>show me / hide me</div>
<a class="showhide">BBB</a>
<div>show me / hide me</div>
js
$('.showhide').click(function(e) {
$(this).next().slideToggle();
e.preventDefault(); // Stop navigation
});
$('div').hide();
Am just posting this in case someone was trying to answer.