Javascript / Jquery onclick function condensation - javascript

I was wondering if what can I do with my codes to make it shorter.
Here is my code, it is like a simple tabs.
Btw, this codes are already working, but I'm thinking that if i have many tabs then I have to repeat many click functions.
Is there a way to make my script shorter, Thanks in advance.
$(function () {
$(".invMer, .invEq").hide();
$(".mergers a").click(function () {
$(".invMer").fadeIn();
$(".invEq, .invPe").hide();
});
$(".equity a").click(function () {
$(".invEq").fadeIn();
$(".invMer, .invPe").hide();
});
$(".privateEq a").click(function () {
$(".invPe").fadeIn();
$(".invMer, .invEq").hide();
});

Give all the links the same class, and a data attribute that says which tab it should open. So something like:
<div class="mergers">
<a class="tablink" href="#" data-tab="invMer">Mergers</a>
</div>
And all the tab DIVs should also have a common class:
<div class="tabdiv" id="invMer">
...
</div>
Then you can use a single handler:
$(".tablink").click(function() {
var tab = '#' + $(this).data("tab");
$(".tabdiv").not(tab).hide();
$(tab).show();
});

Use a data attribute
<a data-show=".invPe">
and do
$("a[data-show]").on("click", function () {
var selector = $(this).data("show");
$(".invMer, .invEq, .invPe").hide();
$(selector).fadeIn();
});

Related

Find link from closest li and open it in a new page - Javascript

I have a submenu divided in two parts:in the right side a li which contains a link and in the left side an icon for each li.
Icons use a css class,called 'submenubtn'.I want to make a javascript function which takes the link from the closest li,assign to that icon,and when that icon is clicked,the link should be open in a new tab.
I hope I was clear enough,please ask me anything you didnt'n undertand.
here is the code i have until now:
$(document).ready(function() {
$("body").on("click", ".submenubtn", function() {
var link = $(this).find("li").attr('href');
//window.alert(link);
window.open(link)
});
});
link returns "undifined".
I don't know how much this will help,but the html page:
<?Menu?>
<div id="<?$_name?>" class="atk-menu atk-menu-vertical atk-popover">
<ul>
<?Item?>
<?MenuItem?>
<li id="<?$id?>" class="<?$class?>"> <i class="<?$icon?>"></i><?label?>MenuItem<?/?></li>
<?/MenuItem?>
<?/?>
<?$Content?>
</ul>
</div>
<?MenuSeparator?><?/MenuSeparator?>
<?/?>
EDIT I solved the problem..see in my answer the solution
Use window.location.href = link;
and closest() function of JQuery to get what you want
To open it on a new window add window.open(link, '_blank')
i think using data tags is the solution
here the soure: http://api.jquery.com/data/
new li html:
<li data-url="HERE THE URL!"/>
your new jQuery:
$(document).ready(function() {
$("body").on("click", ".submenubtn", function() {
var link = $(this).closest('li').data('url');
//window.alert(link);
window.open(link)
});
});
li element cannot contain href attribute, you can give your li a data attribute such as:
<li data-href="your url here"></li>
then you can use:
$(document).ready(function () {
$("body").on("click", ".submenubtn", function () {
var link = $(this).closest('li').data('url');
window.open(link, '_blank');
});
});
find() used to find the descendants of your element which is not applicable in your case since your anchor is the child of your li element.
So you need to use closest() to traverse up the DOM tree and get the closest parent li instead.
Try to use:
$(document).ready(function () {
$("body").on("click", ".submenubtn", function () {
var link = $(this).closest('li').find('a').attr('url');
window.location.href(link);
});
});
Problem solved
I managed to solve this...it was pretty simple.
$(document).ready(function() {
$(".submenubtn").click(function() {
a = $(this).closest('a').attr('href');
window.open(a);
return false;
});
});

How to optimize jQuery code for adding classes (to different elements)?

Example HTML (for the sake of clarity):
<nav>
<ul>
<li class="top-navbar-channels">
<div class="dropdown-menu">BLAH, BLAH, BLAH!</div>
</li>
<li class="top-navbar-about">
<div class="dropdown-menu-about">BLAH, BLAH, BLAH!</div>
</li>
<li class="top-navbar-search">
<div class="dropdown-menu-search">BLAH, BLAH, BLAH!</div>
</li>
</ul>
</nav>
Example jQuery code:
jQuery(document).ready(function($){
$('.dropdown-menu').on('show', function () {
$('.top-navbar-channels > a').addClass('selected');
});
$('.dropdown-menu').on('hide', function () {
$('.top-navbar-channels > a').removeClass('selected');
});
$('.dropdown-menu-about').on('show', function () {
$('.top-navbar-about > a').addClass('selected');
});
$('.dropdown-menu-about').on('hide', function () {
$('.top-navbar-about > a').removeClass('selected');
});
$('.dropdown-menu-search').on('show', function () {
$('.top-navbar-search > a').addClass('selected');
});
$('.dropdown-menu-search').on('hide', function () {
$('.top-navbar-search > a').removeClass('selected');
});
});
For those who are curious... the jQuery code adds a new class selected to the active menu item's link. In my case it's Twitter Bootstrap-based collapsible menu, where active means, the menu item is not collapsed i.e. open.
Now, the question is, can the jQuery code be optimized (i.e. same functionality with less code)? If so, how?
Add a common class to common main elements so you can use that single class as the selector. You can also combine the events into one on() call and use toggleClass() on the link. on() allows for multiple space separated events
Example
<div class="dropdown-menu menu_content">
Then for jQuery:
$('.menu_content').on('show hide', function () {
$(this).siblings("a").toggleClass('selected');
});
Perhaps, this code:
jQuery(document).ready(function($){
var $menus = $('.dropdown-menu, .dropdown-menu-search, .dropdown-menu-about');
$menus.on('show', function () {
$(this).siblings("a").addClass('selected'); // or alternatively, $(this).prev("a")
});
$menus.on('hide', function () {
$(this).siblings("a").removeClass('selected'); // idem as above
});
});
This is a little shorter then Matthias... not very much shorter
$(function(){
$('.dropdown-menu, .dropdown-menu-search, .dropdown-menu-about').on('show',function(){
$(this).siblings('a').addClass('selected');
}).on('hide',function(){
$(this).siblings('a').removeClass('selected');
});
});

Hide/show DIVs in JS no longer working - potential conflict btw scripts

I used this tutorial to hid/show DIVs. Unfortunately for some reason it's no longer working (I modified a few things in my code in the meantime)... Do you see where the issue come from? jsfiddle: http://jsfiddle.net/Grek/C8B8g/
I think there's probably a conflict btw the 2 scripts below:
function showonlyone(thechosenone) {
$('.textzone').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(200);
}
else {
$(this).hide(200);
}
});
}
$('.activity-title a').click(function(){
$('.textzone').fadeOut(2000);
var region = $(this).attr('data-region');
$('#' + region).fadeIn(2000);
})​
You have a few problems going on. You're missing data-source on your <a> elements. Their "region-source" is hidden inside of the href with some function. I removed that put it into data-source and now it all works fine.
You want to do something like this:
$('.activity-title a').click(function(){
var region = $(this).attr('data-region');
$('.textzone:visible').fadeOut(2000, function () {
$('#' + region).fadeIn(2000);
});
return false; // stops href from happening
})​;
// HTML Structured like so:
<div class="source-title-box"><span class="activity-title">
Our region</span>
</div>
jsFiddle DEMO
I assume from your markup in the jsFiddle that for every link (.activity-title a), there is a .textzone. I removed the onclick event from these anchors. This way The first link corresponds with the first .textzone:
<div id="source-container">
<div id="source-region" class="textzone">
<p><span class="activity-title">Interacting with the nature</span></p>
<p>blablabla</p>
</div>
<div id="source-oursource" class="textzone">
<p><span class="activity-title">Pure, pristine, and sustainable source</span></p>
<p>blablabla</p>
</div>
<div class="source-title-box"><span class="activity-title">Our region</span></div>
<div class="source-title-box"><span class="activity-title">Our source</span></div>
</div>​
Then with the script I simply use the index of the link which is clicked to determine the appropriate .textzone to show:
var textZones = $(".textzone");
var anchors = $('.activity-title a').click(function(e){
e.preventDefault();
var index = anchors.index(this);
textZones.filter(":visible").fadeOut(2000, null, function() {
textZones.eq(index).fadeIn(2000);
});
})​

jQuery show / hide not working

Tried to look at all the other questions about why this isn't working, no luck. I'm loading this in my header:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
Here is my script:
$(document).ready(function() {
$("#knee-tab").hide();
$("#shoulder-tab").hide();
});
$(function () {
$("#patient-portal-link").click (function (event) {
$("#patient-portal-tab").show();
$("#knee-tab").hide();
$("#shoulder-tab").hide();
});
});
$(function () {
$("#knee-link").click (function (event) {
$("#patient-portal-tab").hide();
$("#knee-tab").show();
$("#shoulder-tab").hide();
});
});
$(function () {
$("#shoulder-link").click (function (event) {
$("#patient-portal-tab").hide();
$("#knee-tab").hide();
$("#shoulder-tab").show();
});
});
Here are the links that are meant to call up the script:
<ul>
<li><a id="#patient-portal-link">Patient Portal</a></li>
<li><a id="#knee-link">Knee</a></li>
<li><a id="#shoulder-link">Shoulder</a></li>
</ul>
And then I have the three divs which are named as follows:
<div id="patient-portal-tab">Patient portal content</div>
<div id="knee-tab">Knee content</div>
<div id="shoulder-tab">Shoulder content</div>
The knee and shoulder divs hide correctly on page load, but the links do nothing. I'm using Google Chrome and when inspecting element, I get no errors reported for javascript. What am I doing wrong?
Remove the # characters from your ID values. The # character in jQuery denotes an ID of an element, so you would need two #'s (##knee-tab) for this to work.
Are you sure you have the # symbol infront of the Ids. ReWrite it like this and it will work
<li><a id="patient-portal-link">Patient Portal</a></li>
<li><a id="knee-link">Knee</a></li>
<li><a id="shoulder-link">Shoulder</a></li>
your problem is in your HTML code. The id's in HTML doesn't need the hash '#'.
$(function() ... ) is just shorthand for $(document).ready(function() ...) if i recall correctly. So you are using too many ready calls. Try this:
$(document).ready(function() {
$("#knee-tab").hide();
$("#shoulder-tab").hide();
$("#patient-portal-link").click (function (event) {
$("#patient-portal-tab").show();
$("#knee-tab").hide();
$("#shoulder-tab").hide();
});{
$("#knee-link").click (function (event) {
$("#patient-portal-tab").hide();
$("#knee-tab").show();
$("#shoulder-tab").hide();
});
$("#shoulder-link").click (function (event) {
$("#patient-portal-tab").hide();
$("#knee-tab").hide();
$("#shoulder-tab").show();
});
});
Click here
check this fiddle
in this code you have entered extra # to the id
overwrite your previous html to the html code given in fiddle

Combining document ready scripts?

I'm using a simple show-hide script on various IDs. The issue is as it stands right now each is a seperate JS that calls the document ready function via jQuery.
Is there a way to combine this into one more flexible script or at least into one script in some form or another. Thank you so much for your time in advance!
Below is an example:
<script type="text/javascript">
$(document).ready(function () {
$("#loadDummy7").hover(
function () {
$("#dummy7").show();
}, function () {
$("#dummy7").hide();
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#loadDummy8").hover(
function () {
$("#dummy8").show();
}, function () {
$("#dummy8").hide();
});
});
</script>
You can combine it into a single script like this:
$(function(){
$("[id^='loadDummy']").hover(function() {
$("#" + this.id.replace('loadD', 'd')).toggle();
});
});
This uses the attribute-starts-with selector to get all id="loadDummyXXX" controls and finds the element to toggle with the corresponding dummyXXX ID. An easier way would be to use classes and find it relatively, for example if your markup was like this:
<div class="dummyWrapper">
Stuff
<div class="dummy" style="display: none;"> More Stuff</div>
</div>
You could do it like this, much cleaner:
$(function(){
$(".dummyWrapper").hover(function() {
$(this).find(".dummy").toggle();
});
});

Categories