Unexpected order in script execution - javascript

Why is it running the second script and how can I make it work like a toggle control?
<script>
var el = 2;
$(document).ready(function(){
$(".rightDiv").click(function(){
if (el == 2) {
$(this).animate({left:'150px'});
el = 1;
}
});
});
</script>
<script>
$(document).ready(function(){
$(".rightDiv").click(function(){
if (el==1) {
$(this).animate({left:'50px'});
el = 2;
}
});
});
</script>

You only need one .ready()
$(document).ready(function()
{
var el = false;
var rightDivs = $('.rightDiv');
$(rightDivs).click(function(){
if (el == false)
{
$(this).animate({left:'150px'});
el = true;
}
else if (el == true)
{
$(this).animate({left:'50px'});
el = false;
}
});
});

This should work fine for you:
var el = false;
$(document).ready(function() {
$(".rightDiv").click(function() {
$(this).stop(true).animate({left: (el ? 50 : 150) + 'px'});
el = !el;
});
});​
jsfiddle with example

You have atteached two event handlers, so when the event happens it will run one, then the other.
As the first one will change the variable so that the condition in the second one becomes true, the code inside both if statements will run.
Put the code in the same event handler, so that you can use else to run only one of them:
<script>
$(document).ready(function(){
var el = 2;
$(".rightDiv").click(function(){
if (el == 2) {
$(this).animate({left:'150px'});
el = 1;
} else {
$(this).animate({left:'50px'});
el = 2;
}
});
});
</script>

here's a slightly improved version of #h2ooooooo 's answer, where we ditched the global scoped variable and use element's attributes.
Basically what we are doing here is to prevent bloating the global scope by using global variables and now we are working with data directly related to the element that was pressed.
$(document).ready(function() {
$(".rightDiv").attr("isLeft",1).click(function() {
var pos = "50";
if( $(this).attr("isLeft") == "1" ){
pos = "150";
$(this).attr("isLeft",0)
}else{
$(this).attr("isLeft",1);
}
$(this).stop(true).animate({left: pos + 'px'});
});
});

Related

After first click of radio button can not fire change event

My jquery change event of radio button not working after first click and does not give any error please help me. i stuck in this from last week.and also cant count proper value because of this problem.
$('input[name="emailing"]').change(function()
{
checkValue();
});
function checkValue(evt) {
alert('hi');
var package = $("#package_value").val();
var emailing = $('input[name="emailing"]:checked').val();
$('input[name="emailing"]').on("mousedown", function() {
var select = $('input[name="emailing"]:checked').val();
$("#selected").val(select);
}).on("mouseup", function() {
$('input[name="emailing"]').prop('checked', false);
$(this).prop('checked', true).checkboxradio("refresh");
});
var selected = $("#selected").val();
alert(selected);
var update = $("#update").val();
if(update != '')
{
var hiddenPackage = $("#hidden_pricing").val();
var hiddenRadion = $("#hidden_radio").val();
var totalValue = package - hiddenRadion;
if(emailing == 1)
{
$("#package_value").val('');
var value = Number(totalValue) + 38;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 2)
{
$("#package_value").val('');
var value = Number(totalValue) + 55;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 0)
{
$("#package_value").val('');
var value = Number(totalValue) + 0;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
}
}
You should use delegate
$(document).delegate( "input[name='emailing']", "change", function() {
checkValue();
});
Use on() function with any element id instead of (document)
$(document).on('change', 'input[name="emailing"]', function() {
checkValue();
});

conflicting scripts not functioning

I have using 2 scripts declared on my footer. each script works perfectly when declared alone but if I declared the second one. the other function the other not.
Here is the code that works when declared alone and with the other script.
This has his own js file.
var fixed = false;
$(document).scroll(function() {
if( $(this).scrollTop() > 20 ) {
if( !fixed ) {
fixed = true;
$('.navbar-fixed-top').addClass('scroll');
}
} else {
if( fixed ) {
fixed = false;
$('.navbar-fixed-top').removeClass('scroll');
}
}
});
/*
* Smooth Scroll
*/
$(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
// Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
$('a[href*=#]').each(function() {
// Ensure it's a same-page link
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
// Ensure target exists
var $target = $(this.hash), target = this.hash;
if (target) {
// Find location of target
var targetOffset = $target.offset().top;
$(this).click(function(event) {
// Prevent jump-down
event.preventDefault();
// Animate to target
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
// Set hash in URL after animation successful
location.hash = target;
});
});
}
}
});
// Use the first element that is "scrollable" (cross-browser fix?)
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
The other one is this declared below the first script. now this didn't work when the other is present but works perfectly when alone. also I tried the no conflicting script but same goes for the result.
<script>
$(document).ready(function(){
$(function(){
document.querySelector( "#nav-toggle" )
.addEventListener( "click", function() {
this.classList.toggle( "active" );
$(".navmobile").slideToggle();
});
});
$(window).resize(function() {
if ($(window).width() >= 767) {
$(".navmobile").hide();
}
else {
$("#nav-toggle").removeClass("active");
$(".navmobile").hide();
}
});
});
</script>
You probably have this element in your code:
Note the href="#" part - the first script is using event.preventDefault() for every A element with href that containing "#", so the second script doesn't get click event. remove the href="#" from that element (or leave the attribute empty) and it should work.
Change
// Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
$('a[href*=#]').each(function() {
to
// Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
$('a[href*=#]').not("#av-toggle").each(function() {
so the first script ignore the link you are clicking to do the toggling.

Jquery : swap two value and change style

i need to make a script for select a black div by click(go red), and put black div value into a white div value by another click, this is ok but when i try to swap values of two white case, the change do correctly one time, but if i retry to swap two value of white case the values swap correctly but whitout the background color red.
This is my code :
var lastClicked = '';
var lastClicked2 = '';
$(".blackcase").click(function(e) {
var i = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.blackcase').removeClass('red');
if (lastClicked != this.id) {
$(this).addClass('red');
var currentId = $(this).attr('id');
var currentVal = $(this).html();
$(".whitecase").click(function(e) {
$('.blackcase').removeClass('red');
var currentId2 = $(this).attr('id');
if (i <= 0 && $("#" + currentId2).html().length == 0) {
$("#" + currentId2).html(currentVal);
$("#" + currentId).html("");
i = 1;
}
});
} else {
lastClicked = this.id;
}
}
});
$(".whitecase").click(function(e) {
var j = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.whitecase').removeClass('red');
if (lastClicked2 != this.id) {
$(this).addClass('red');
var currentId0 = $(this).attr('id');
var currentVal0 = $(this).html();
$(".whitecase").click(function(e) {
e.preventDefault();
var currentId02 = $(this).attr('id');
var currentVal02 = $(this).html();
if (j <= 0 && currentVal0 != currentVal02) {
$('.whitecase').removeClass('red');
$("#" + currentId02).html(currentVal0);
$("#" + currentId0).html(currentVal02);
j = 1;
return false;
}
});
} else {
lastClicked2 = this.id;
}
}
});
This is JSfiddle :
https://jsfiddle.net/12gwq95u/12/
Try to take 12 and put into first white case, put 39 into second white case, click on the white case with 12 (go red) then click on the white case with 39, the values swap correctly with the red color when it's select, but if you try to reswap two whitecase values thats work but without the red color.
Thanks a lot
I have spent some time to rewrite your code to make it more clear. I don't know what exactly your code should do but according to the information you have already provided, my version of your code is the following:
var selectedCase = {color: "", id: ""};
function removeSelectionWithRed() {
$('div').removeClass('red');
}
function selectWithRed(element) {
removeSelectionWithRed();
element.addClass('red');
}
function updateSelectedCase(color, id) {
selectedCase.color = color;
selectedCase.id = id;
}
function moveValueFromTo(elemFrom, elemTo) {
elemTo.html(elemFrom.html());
setValueToElem("", elemFrom);
}
function setValueToElem(value, elem) {
elem.html(value);
}
function swapValuesFromTo(elemFrom, elemTo) {
var fromValue = elemFrom.html();
var toValue = elemTo.html();
setValueToElem(fromValue, elemTo);
setValueToElem(toValue, elemFrom);
}
function isSelected(color) {
return selectedCase.color == color;
}
function clearSelectedCase() {
selectedCase.color = "";
selectedCase.id = "";
}
function elemIsEmpty(elem) {
return elem.html().length == 0;
}
$(".blackcase").click(function (e) {
if (elemIsEmpty($(this))) {
return;
}
alert("black is selected");
selectWithRed($(this));
updateSelectedCase("black", $(this).attr("id"), $(this).html());
});
$(".whitecase").click(function (e) {
removeSelectionWithRed();
if (isSelected("black")) {
alert("moving black to white");
moveValueFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
if(isSelected("white") && selectedCase.id !== $(this).attr("id")) {
alert("swap whitecase values");
swapValuesFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
alert("white is selected");
selectWithRed($(this));
updateSelectedCase("white", $(this).attr("id"), $(this).html());
});
Link to jsfiddle: https://jsfiddle.net/12gwq95u/21/
If my answers were helpful, please up them.
It happens because you have multiple $(".whitecase").click() handlers and they don't override each other but instead they all execute in the order in which they were bound.
I advise you to debug your code in browser console by setting breakpoints in every click() event you have (in browser console you can find your file by navigating to the Sources tab and then (index) file in the first folder in fiddle.jshell.net).
In general I think you should rewrite you code in such a way that you won't have multiple handlers to the same events and you can be absolutely sure what your code does.

How to use javascript conditions correctly?

I have a slider function, which works perfectly fine with moveRight() but I am stuck, and can use it only once.
I decided to use a condition to disable the move function and change the attributes of links on the second click. My code below:
$('#control_next').click(function () {
var used = 0;
if (used == 0) {
moveRight();
used = 1;
} else if (used == 1) {
$('.control_next').attr('href', '#business-events');
$('.control_next').addClass( "url" );
}
alert(used);
});
You have to place the varaible used outside your event handler because else it will always be 0 with every click:
var used = 0;
$('#control_next').click(function () {
if (used == 0) {
moveRight();
used = 1;
}
else if (used == 1) {
$('.control_next').attr('href', '#business-events');
$('.control_next').addClass( "url" );
}
alert(used);
});
You should declare variable Globally. Like
var used = 0;
$('#control_next').click(function () {
if (used == 0) {
moveRight();
used = 1;
}
else if (used == 1) {
$('.control_next').attr('href', '#business-events');
$('.control_next').addClass( "url" );
}
});

Conflict between two js scripts, I can't understand why?

I am trying to implement a tracking script that standalone and on other sites works just as intended (or atleast to what I can see from watching the sites and analytics).
The code looks like this
{
jQuery(document).ready(function($) {
var filetypes = /\.(zip|exe|dmg|pdf|doc.*|xls.*|ppt.*|mp3|txt|rar|wma|mov|avi|wmv|flv|wav)$/i;
var baseHref = '';
if (jQuery('base').attr('href') != undefined) baseHref = jQuery('base').attr('href');
jQuery('a').on('click', function(event) {
var el = jQuery(this);
var track = true;
var href = (typeof(el.attr('href')) != 'undefined' ) ? el.attr('href') :"";
var isThisDomain = href.match(document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0]);
if (!href.match(/^javascript:/i)) {
var elEv = []; elEv.value=0, elEv.non_i=false;
if (href.match(/^mailto\:/i)) {
elEv.category = "Email";
elEv.action = "Klick";
elEv.label = href.replace(/^mailto\:/i, '');
elEv.loc = href;
}
else if (href.match(filetypes)) {
var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
elEv.category = "Nerladdning";
elEv.action = "Fil-" + extension[0];
elEv.label = href.replace(/ /g,"-");
elEv.loc = baseHref + href;
}
else if (href.match(/^https?\:/i) && !isThisDomain) {
elEv.category = "Ex.Länk";
elEv.action = "Klick";
elEv.label = href.replace(/^https?\:\/\//i, '');
elEv.non_i = true;
elEv.loc = href;
}
else track = false;
if (track) {
_gaq.push(['_trackEvent', elEv.category.toLowerCase(), elEv.action.toLowerCase(), elEv.label.toLowerCase(), elEv.value, elEv.non_i]);
if ( el.attr('target') == undefined || el.attr('target').toLowerCase() != '_blank') {
setTimeout(function() { location.href = elEv.loc; }, 400);
return false;
}
}
}
});
});
}
This is the jquery version that is loaded before
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
Now onto the problem, if I place "my" script above the ones I will post below then my script works. But if I do it as I want, placing my script last on the page it does not work, or anywhere aslong as it is below the other one will end up with mine not working
<script type="text/javascript"> jQuery(document).ready(function ($) { runJS(); }); </script>
The runJS leads to another .js file that is functions.js, of what I can understand runJS is this (I replaced the name of the site with site below).
function runJS() {
if((fontLoaded('DistrictThin') && fontLoaded('NationalLight')) || timer > 30) {
site.init();
$(".search_result").find('img').load(function () {
$(".search_result.primary").equalHeights();
//$(".search_result:not(.primary)").equalHeights();
});
if ($('#site_search_form').length > 0) {
populateForm();
}
}
else {
setTimeout('runJS()', 100);
timer += 1;
}
}
Any help would be much appreciated!
if you using different version of jquery in single page you must use this
var jq = jQuery.noConflict (); // jq having the value of $.
// In your entire script use jq instead of $.

Categories

Resources