Trigger function and open URL at the same time - javascript

I am creating a counter which counts the number of clicks made to an anchor tag. I also need the URL to be opened at the same time. I tried the below code. The page is redirected before the function executes.
Is there a better way to do this?
Code:
$(document).ready(function () {
var $res = $('#counter').text($.cookie('link-count') || 0)
$('a').click(function () {
var count = parseInt($.cookie('link-count'), 10) || 0;
count++;
if (count > 10) {
$(this).attr("href", "https://www.yahoo.com");
}
$.cookie('link-count', count);
$res.text(count);
location.href = $(this).attr("href");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Google
<div id="counter">0</div>

var linkCount;
$(document).ready(function () {
var $res = $('#counter').text(linkCount || 0)
$('a').click(function (e) {
e.preventDefault();
var count = parseInt(linkCount) || 0;
count++;
if (count > 10) {
$(this).attr("href", "https://www.yahoo.com");
}
linkCount = count;
$res.text(count);
location.href = $(this).attr("href")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Google
<div id="counter">0</div>

Related

Showing multiple sticky header while scroll down the webpage

I am a beginner in jQuery. As willing to develop a mobile website, I would like to implement sticky header for enhancing the user experiences.
Here are some codes of my work but it seems not work as calculation of the "top".
HTML:
<div class="fixed-header">
<div class="header_item" id="head_a"> A </div>
<div class="header_item" id="head_b"> B </div>
<div class="header_item" id="head_c"> C </div>
<div class="header_item" id="head_d"> D </div>
<div class="header_item" id="head_e"> E </div>
</div>
javascript and jQuery:
var $totalImageHeight;
$(window).on("load", function() { //Fires when DOM is loaded
getImageSizes();
$(window).resize(function() { //Fires when window is resized
getImageSizes();
});
});
function getImageSizes() {
$(".insurance_item img").each(function(count) {
var $this = $(this);
$imageHeight = $this.height();
$totalImageHeight = $imageHeight * (count + 1);
});
}
var stickyHeaders = (function() {
var $window = $(window),
$stickies;
var load = function(stickies) {
if (typeof stickies === "object" && stickies instanceof jQuery && stickies.length > 0) {
$stickies = stickies.each(function() {
var $thisSticky = $(this).wrap('<div class="followWrap" style="height: 0;"/>');
$thisSticky
.data('originalPosition', $thisSticky.offset().top)
.data('originalHeight', $thisSticky.outerHeight( 75 ))
.parent().height($thisSticky.outerHeight( 75 ));
});
$window.off("scroll.stickies").on("scroll.stickies", function() {
_whenScrolling();
});
}
};
var _whenScrolling = function() {
$stickies.each(function(i) {
var $thisSticky = $(this),
$stickyPosition = $thisSticky.data('originalPosition');
if ($stickyPosition <= $window.scrollTop()) {
var $nextSticky = $stickies.eq(i + 1);
$nextStickyPosition = $totalImageHeight - $nextSticky.data('originalPosition') - $thisSticky.data('originalHeight');
$thisSticky.addClass("fixed").css("top", $nextStickyPosition);
if ($nextSticky.length > 0 && $thisSticky.offset().top >= $nextStickyPosition) {
$thisSticky.addClass("absolute").css("top", $nextStickyPosition);
}
}else{ //scroll up and disable the fixed header
var $prevSticky = $stickies.eq(i - 1);
$thisSticky.removeClass("fixed");
if($prevSticky.length>0&&$window.scrollTop()<=
$thisSticky.data('originalPosition') -
$thisSticky.data('originalHeight')){
$prevSticky.removeClass("absolute").removeAttr("style");
}
}
});
};
return {
load: load
};
})();
$(function() {
stickyHeaders.load($(".header_item"));
});
Sorry for the late answer. I create an new javascript for implementing this function.
Code:
var $window = $(window);
var imageArr = [];
var iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
console.log(iOS);
$(window).on("load", function() { //Fires when DOM is loaded
getImageSizes();
window.requestAnimationFrame(tick);
$(window).resize(function() { //Fires when window is resized
getImageSizes();
scrollDetect(imageArr);
});
});
function getImageSizes() { //get the numbers of images and its outerHeight
var $items = $(".insurance_item");
for(var c = 0; c < $items.length; c++){
imageArr[c] = $($items[c]).outerHeight();
}
}
function scrollDetect(imageArr){ //show the title header of image once the image is offscreen.
var $items = $('.header_item');
for(var c = 0; c < imageArr.length; c++){
if($window.scrollTop() >= (imageArr[c] * (c+1)) - $('#fixed-header').outerHeight()){
$items.eq(c).show();
}else{
$items.eq(c).hide();
}
}
window.requestAnimationFrame(tick); //prevent the frame lost and make a incorrect calculation
}
function tick(){
scrollDetect(imageArr);
};
May be some better solution for solving this situation, thanks for everyone.

how to limit the click event in jquery loop?

I would like to limit click event loop in jquery. I have categories list which will have in the following format and also after 5 click in the loop i have to disable click event.
<div class="col-md-2 col-sm-4 col-xs-6 home_s">
<a class="get_category" id="36" href="javascript:void(0)">
<img class="img-responsive img-center" src="">
<span>xxxxx</span>
</a>
<input type="hidden" value="36" id="categories36" name="categories[]">
</div>
$(document).ready(function() {
$(".get_category").on('click', function() {
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
})
});
You can use off() to unbind event handler
$(document).ready(function() {
// variable for counting clicks
var i = 1;
var fun = function() {
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
// checking and increment click count
if (i++ == 5)
// unbinding click handler from element
$(".get_category").off('click', fun);
};
$(".get_category").on('click', fun);
});
Example :
$(document).ready(function() {
var i = 1;
var fun = function() {
alert('clicked'+i);
if (i++ == 5)
$(".get_category").off('click', fun);
};
$(".get_category").on('click', fun);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="get_category">click</button>
If you have multiple .get_category in your html the solution from Pranav C Balan won't work.
$(document).ready(function() {
function clickFunc() {
var click_count = $(this).data('click-count') || 0;
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
if (++click_count >= 5)
$(this).off('click', clickFunc);
$(this).data('click-count', click_count);
});
$(".get_category").on('click', clickFunc);
});
This way you store the click count on the data-click-count attribute of each .get_category

Updating interval dynamically - jQuery or Javascript

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" />

Writing Text Effect with jquery

I am use this code for Writing Text Effect:
<script type="text/javascript">
$(document).ready(function () {
function changeText(cont1, cont2, speed) {
var Otext = cont1.text();
var Ocontent = Otext.split("");
var i = 0;
function show() {
if (i < Ocontent.length) {
cont2.append(Ocontent[i]);
i = i + 1;
};
};
var Otimer = setInterval(show, speed);
};
$(document).ready(function () {
changeText($("#TypeEffect p"), $(".p2"), 150);
});
});
</script>
but its not working for multiline, I use this code:
changeText($("#TypeEffect p, #TypeEffect br"), $(".p2"), 150);
so, its not working.
please help me for Writing Text Effect in multi line.
Try
$(document).ready(function () {
function changeText(cont1, cont2, speed) {
var contents = $(cont1).contents().map(function () {
if (this.nodeType == 3) {
if ($.trim(this.nodeValue).length) {
return this.nodeValue.split("")
}
} else {
return $(this).clone().get();
}
}).get();
var i = 0;
function show() {
if (i < contents.length) {
cont2.append(contents[i]);
i = i + 1;
} else {
clearInterval(Otimer)
}
};
var Otimer = setInterval(show, speed);
};
$(document).ready(function () {
changeText($("#TypeEffect p"), $(".p2"), 150);
});
});
Demo: Fiddle
Try this:
$("[class*=autoWrite]").each(function(e){
autoWriteText($(this));
})
function autoWriteText(elm){
var clas = elm.attr("class");
clas = clas.split("-");
var speed = clas[1];
var delay = clas[2];
var txt = elm.html();
elm.html("");
setTimeout(function(){
elm.fadeIn("fast");
txt = txt.split("");
var txtI = 0;
var html = "";
var intrvl = setInterval(function(){
html = html + txt[txtI] ;
elm.html(html + "_");
txtI = txtI + 1;
if(txtI == txt.length){
clearInterval(intrvl);
}
},speed);
},delay)
}
.autoWriteText{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<h5 class="autoWrite-10-0" >This element will write a <b>letter every 10 milliseconds</b> in this box, with a <b>delay of 0 milliseconds</b>.</h5>
<hr>
<h5 class="autoWrite-50-1000" >This element will write a <b>letter every 50 milliseconds</b> in this box, with a <b>delay of 1 second</b>.</h5>
<hr>
<h5 class="autoWrite-200-3000" >This element will write a <b>letter every 200 milliseconds</b> in this box, with a <b>delay of 3 second</b>.</h5>
<hr>
<h5 class="autoWrite-500-5000" >This element will write a <b>letter every 500 milliseconds</b> in this box, with a <b>delay of 5 second</b>.</h5>
<hr>

Show and Hide functions using Jquery

I am new for jquery, Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$('.toAdd').hide();
var count = 0;
$('#add').on('click', function () {
$('.toAdd:eq(' + count + ')').show();
count++;
});
});
</script>
<div class="toAdd">One</div><div class="toAdd">Two</div><div class="toAdd">Three</div>
<input type="button" value="show" id="add"/>
<input type="button" value="hide" id="sub"/>
In this code if i click show button the divisions one by one it showing. after that i need to hide one by one if i click hide button
Fiddle here
$(document).ready(function () {
$('.toAdd').hide();
var count = 0;
$('#add').on('click', function () {
$('.toAdd:eq(' + count + ')').show();
count++;
});
var deCount = count;
$('#sub').on('click', function () {
count--;
$('.toAdd:eq(' + count + ')').hide();
});
});
Hope this might help you... :)
$('#sub').on('click', function () {
if(count > 0){
count--;
$('.toAdd:eq(' + count + ')').hide();
}
});
Edited jsfiddle by Outlooker
if($('.toAdd:eq(' + count + ')').is('*'))
Added check of item existance.
Fiddle
Try this too
<script type="text/javascript">
$(document).ready(function () {
$('.toAdd').hide();
$('#add').on('click', function () {
$('.toAdd,.hidden').first().show().addClass( "shown" ).removeClass( "hidden" );
});
$('#sub').on('click', function () {
$('.toAdd,.shown').last().hide().addClass( "hidden" ).removeClass( "shown" );
});
});
The answer of Outlooker is right but have some little bit error. when user will click on show button 4th time then your hide doesn't work as expected. So I just fix the chunk here and sharing with you guys.
Html Code:
<div class="toAdd">One</div>
<div class="toAdd">Two</div>
<div class="toAdd">Three</div>
<input type="button" value="show" id="add" />
<input type="button" value="hide" id="sub" />
Java Script Code:
/**
* Hide all Content div
*/
$(".toAdd").hide();
/**
* Total no of content div find out
**/
var lengthDiv = $(".toAdd").length;
/**
* Default count declare
**/
var count = 0;
/**
* Click on show button
**/
$('#add').on('click', function () {
if (count < lengthDiv) {
$('.toAdd:eq(' + count + ')').show();
count++;
}
});
/**
* Click on hide button
**/
$('#sub').on('click', function () {
if (count > 0) {
count--;
$('.toAdd:eq(' + count + ')').hide();
}
});
Fiddle Example
Try this this will work you very fine
$('.toAdd').hide();
$('#add').click(function(){
$('div').each(function(key, value) {
$(value).delay(key * 500).fadeIn(500);
});});
$('#sub').click(function(){
$('div').each(function(key, value) {
$(value).delay(key * 500).fadeOut(500);
});
});
Fiddle Here
Try
var $toAdds = $('.toAdd').hide();
var count = 0;
$('#add').on('click', function () {
if (count < $toAdds.length) {
$toAdds.eq(count).show();
count++;
}
});
$('#sub').on('click', function () {
if (count > 0) {
count--;
$toAdds.eq(count).hide();
}
});
Demo: Fiddle

Categories