Best way to combine identical parts of code - javascript

Below is my code I've developed some time ago. Everything works fine, but I think it'd be better to combine the code parts. Unfortunately, I'm not an expert in JavaScript yet so can't understand how to improve the combining. Much appreciate any help & advice:
jQuery(function() {
jQuery('.price').hide();
jQuery('.d2').show();
jQuery('#select').on("change", function() {
jQuery('.price').hide();
jQuery('.d' + jQuery(this).val()).show();
}).val("2");
});
jQuery(function() {
jQuery('.button').hide();
jQuery('.b2').show();
jQuery('#select').on("change", function() {
jQuery('.button').hide();
jQuery('.b' + jQuery(this).val()).show();
}).val("2");
});
jQuery(function() {
jQuery('.price-2').hide();
jQuery('.e2').show();
jQuery('#select-2').on("change", function() {
jQuery('.price-2').hide();
jQuery('.e' + jQuery(this).val()).show();
}).val("2");
});
jQuery(function() {
jQuery('.button-2').hide();
jQuery('.c2').show();
jQuery('#select-2').on("change", function() {
jQuery('.button-2').hide();
jQuery('.c' + jQuery(this).val()).show();
}).val("2");
});

You can use $ instead of jQuery. Then take the common function out like:
function myFunc($hide, $show, $select) {
$($hide).hide();
$($show + '2').show();
$($select).on("change", function() {
$($hide).hide();
$($show + $(this).val()).show();
}).val("2");
}
$(function() { myFunc('.price', '.d', '#select') });
$(function() { myFunc('.button', '.b', '#select') });
$(function() { myFunc('.price-2', '.e', '#select-2') });
$(function() { myFunc('.button-2', '.c', '#select-2') });

Related

I have a conflict libraries

I have a library conflict problem. My code is like so in template...
<script type="text/javascript">window.jQuery || document.write(unescape(\'%3Cscript src="//code.jquery.com/jquery-1.7.1.min.js"%3E%3C/script%3E\'))</script>
<script type="text/javascript" src="' . $settings['theme'] . '/scripts/qs.js"></script>
';
}.............
And in the qs.js file I have the following
jQuery(document).ready(function($){
$('.sp-body img').each(function() {
$(this).attr({
alt: $(this).attr('src'),
src: smf_default_theme_url + '/images/loading.gif'
});
});
$("body").on("click", ".sp-head", function(event){
$this = $(this);
if ($this.hasClass("unfolded")) {
$this.removeClass("unfolded");
$this.next().slideUp("fast");
$this.next().addClass("folded");
} else {
$this.addClass("unfolded");
$this.next().slideDown("fast");
$this.next().removeClass("folded");
}
c = $this.parent().children('.sp-body');
c.find('img').each(function() {
$(this).attr('src', $(this).attr('alt'));
});
});
$("body").on("click", ".sp-foot", function(event){
$this = $(this).closest("div.sp-body").prev();
if ($this.hasClass("unfolded")) {
$this.removeClass("unfolded");
$this.next().slideUp("fast");
$this.next().addClass("folded");
}
});
});
the mistake is in "$(...).on is not a function" -> $("body").on("click", ".sp-head", function(event){
The problem is in the conflict between libraries. I have looked at the non-conflict mode but I can't get it to work for me, how can I get it to work?
Thanks!!

How to check a radio have onclick with caperjs?

This is my code:
Full code here: http://notepad.cc/casperjsstack1
this.thenOpen('https://www.1800flowers.com/webapp/wcs/stores/servlet/FDDeliveryOptionsDisplayCmd', function() {
this.waitForSelector('#BP-DeliveryCardMess_1', function() {
this.evaluate(function() {
var el = $('#giftMessages.noCard');
el.onclick();
});
});
});
Look at the picture: I want check No Gift Message
I try so much method but all false
Code HTML page here: http://notepad.cc/casperjsstack1_html
Thank you !
Have you tried click()?
this.thenOpen('https://www.1800flowers.com/webapp/wcs/stores/servlet/FDDeliveryOptionsDisplayCmd', function() {
this.waitForSelector('#BP-DeliveryCardMess_1', function() {
this.evaluate(function() {
this.click('#giftMessages.noCard'); // Click the radio button.
});
});
});
Try this.
//jQuery version using evaluation page context
this.thenOpen('https://www.1800flowers.com/webapp/wcs/stores/servlet/FDDeliveryOptionsDisplayCmd', function() {
this.waitForSelector('#BP-DeliveryCardMess_1', function() {
this.evaluate(function() {
$("#giftMessages.noCard").prop("checked", true).trigger("click");
});
});
});
//Casper version using click
this.thenOpen('https://www.1800flowers.com/webapp/wcs/stores/servlet/FDDeliveryOptionsDisplayCmd', function() {
this.waitForSelector('#BP-DeliveryCardMess_1', function() {
this.click("#giftMessages.noCard");
});
});

JQuery Ajax + Dropdown Menu function only runs once

This function only runs once. How can I get it to run multiple times?
I have tried using live() as was suggested in another SO question, but that made no difference to the program.
$(function() {
$('#chooseTeam').live('change', (function() {
$.getJSON($SCRIPT_ROOT + '/_get_info', {
selectedDeck: $('#chooseTeam').val()
}, function(data) {
/* Do something */
});
}
return false;
}));
});
Did you tried with document ready instead of $function()
$(document).ready(function() {
$('#chooseTeam').live('change', (function() {
$.getJSON($SCRIPT_ROOT + '/_get_info', {
selectedDeck: $('#chooseTeam').val()
}, function(data) {
/* Do something */
});
}
return false;
}));
});
Regards

How to generate JQuery calls inside JavaScript FOR loop?

I need to generate this 4 JQuery calls inside a Javascript Function:
$(".dropdown-menu .1_147").hover(
function() { $("#1_147").show(); },
function() { $("#1_147").hide(); }
);
$(".dropdown-menu .2_147").hover(
function() { $("#2_147").show(); },
function() { $("#2_147").hide(); }
);
$(".dropdown-menu .3_147").hover(
function() { $("#3_147").show(); },
function() { $("#3_147").hide(); }
);
$(".dropdown-menu .4_147").hover(
function() { $("#4_147").show(); },
function() { $("#4_147").hide(); }
);
I've write a Javascript function, the FOR loop only generates the last interaction "4_147". How can I tell the Javascript to generate the 4 JQuery calls?
My current JavaScript:
var submenu_navigation = document.getElementsByClassName("dropdown-menu");
var submenu_navigation_list = submenu_navigation[0].getElementsByTagName('li');
/*console.log(submenu_navigation_list);*/
function generateDropdownMenuMoldura(lis_array) {
for (var item in lis_array) {
var item_class_attr_name = lis_array[item].getAttribute('class');
console.log(item_class_attr_name);
$(".dropdown-menu ." + item_class_attr_name).hover(
function() { $("#" + item_class_attr_name).show(); },
function() { $("#" + item_class_attr_name).hide(); }
);
}
}
generateDropdownMenuMoldura(submenu_navigation_list);
Any clues?
Best Regards,
Update:
I got the solution:
/* Define the Elements that I need to loop */
var submenu_navigation = document.getElementsByClassName("dropdown-menu");
var submenu_navigation_list = submenu_navigation[0].getElementsByTagName('li');
function generateDropdownMenuMoldura(lis_array) {
for (var item in lis_array) {
var item_class_attr_name = lis_array[item].getAttribute('class');
console.log(item_class_attr_name);
(function(item_class_attr_name) {
$(".dropdown-menu ." + item_class_attr_name).hover(
function() { $("#" + item_class_attr_name).show(); },
function() { $("#" + item_class_attr_name).hide(); }
);
})(item_class_attr_name);
}
}
generateDropdownMenuMoldura(submenu_navigation_list);
My question is: How this anonymous function call works? This is a recursion technique?
Best Regards,
How to fix your specific solution was already answered in an other question.
But why so complicated? Judging from the JavaScript you currently have, and assuming everything apart from the scope works fine, a simpler solution would be:
$(".dropdown-menu li").hover(function() {
$('#' + this.className).show();
}, function() {
$('#' + this.className).hide();
});
There is no need to bind a different handler to each of these elements, since they all do basically the same thing.
Take a look at jQuery.each('dropdown-menu') method . It is for loops.
HTML Sample
<ul>
<li>foo</li>
<li>bar</li>
</ul>
jQuery Sample
$( "li" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});

jQuery: Unable to fade out a previously faded in element

I want to show a notification at the top – for 2 seconds – telling me which version of jQuery & jQuery UI was loaded. Unfortunately, I can't seem to be able to hide it later.
My code
$('<div>jQuery v' + jQuery.fn.jquery + ' and jQuery UI v' + jQuery.ui.version + ' loaded.</div>')
.addClass('ui-state-highlight').prependTo('body').hide(0, function() {
$(this).fadeIn(500, function() {
setTimeout(function() {
$(this).fadeOut(500, function() {
$(this).remove();
});
}, 2000);
});
});
jQuery Lint says I'm doing something wrong – which is true –, but I don't know how to do it the right way.
It is probably a scope problem. Try:
$(this).fadeIn(500, function() {
var parentContext = $(this);
setTimeout(function() {
parentContext.fadeOut(500, function() {
$(this).remove();
});
}, 2000);
});

Categories

Resources