Condensing/Optimizing jQuery code - javascript

I have the following code for sliding down a hidden content area. It works, but I suspect it's too clumsy and may fire too many requests or events. Can someone suggest a way to combinee these functions more efficiently?
$(".toggler").click(function (event){
event.stopPropagation();
$("#mobile-top").animate({'height':'toggle'}, 250);
});
$("#mobile-top").click(function(event){
event.stopPropagation();
});
$('.toggler').toggle(function() {
$(this).html('Close This Box <em class="fa fa-chevron-up"></em>');
}, function() {
$(this).html('Connect With Us! <em class="fa fa-chevron-down"></em>');
});
$('html').click(function(){
$("#mobile-top").slideUp();
$(".toggler").html('Connect With Us! <em class="fa fa-chevron-down"></em>');
});

I think the code could be improved by using variables when you can especially when using a certain selector more than once.
and try and use ID's not classes.
EDIT
UPDATED JSFIDDLE
Here is the code that is working and wont get confused when you click outside in the HTML area. (note that while naming a variable it can't contain a - character like I had put before)
$(document).ready(function(){
var toggler = $("#toggler");
var mobileTop = $("#mobile-top");
//top drop-down content animation
toggler.click(function(event){
event.stopPropagation();
mobileTop.slideToggle(250);
$(this).toggleClass('open');
$(this).html('Connect With Us! <em class="fa fa-chevron-down"></em>');
$(".open").html('Close This Box <em class="fa fa-chevron-up"></em>');
});
$('html').click(function(){
mobileTop.slideUp(250);
toggler.html('Connect With Us! <em class="fa fa-chevron-down"></em>');
toggler.removeClass('open');
});
$(mobileTop).click(function(event){
event.stopPropagation();
});
});
And this should be more efficient as well.
a good read:
http://code.tutsplus.com/tutorials/10-ways-to-instantly-increase-your-jquery-performance--net-5551

Related

How can I disable Javascript click function if link starts with #

How can I run this code on all links URL except links that start with # like bootstrap collapse, modal links etc.?
$(function(){
$("a").click(function() {
$(".se-pre-con").fadeOut("slow");
$(this).after("<div class='se-pre-con text-center pp500'><i class='fa fa-list fa-spin fa-5x fa-fw text-color1'></i></div>").fadeIn();
});
});
You can simply check the first character to make sure it isn't #.
$(function() {
$("a").click(function() {
if ($(this).attr("href").substr(0, 1) != "#") {
$(".se-pre-con").fadeOut("slow");
$(this).after("<div class='se-pre-con text-center pp500'><i class='fa fa-list fa-spin fa-5x fa-fw text-color1'></i></div>").fadeIn();
}
});
});
You can use the not selector in jquery. Example:
$(function(){
$("a:not([href='#'])").click(function(e){
e.preventDefault();
alert("You clicked me!");
});
});
a { display: block }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click Me!
Click Me Also!
Me Too!
Don't CLick me please!
Don't Click me!
note: preventDefault stops the link from opening
Just use CSS negation and prefix attribute selector:
$('a:not([href^="#"])').click(...)

jQuery events don't work after append [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I'm trying to build my first "serious" webpage. I have just started and I stuck on applying old event listeners on new div section.
I would like to apply all old listeners on $(".novo").append("new div ..")
I have tried to use on() functions but it doesn't seem to work.
And also I have issues when adding new list. It adds to every present div. I want to add it only on clicked div.
<body>
<button class="novo">Novo</button>
<div class="container">
<div class="grupa">
<h1>To-Do List<span id="form"><i class="fas fa-edit"></i></span></h1>
<input type="text" placeholder="Add New Todo">
<ul>
<li><span><i class="fas fa-trash-alt"></i></span> Sabah</li>
</ul>
</div>
<script type="text/javascript" src="Assets\JS\projekt.js">
</script>
</body>
jS:
$("ul").on("click", "li", function(){
$(this).toggleClass("completed");
});
$("ul").on("click", "span", function(event){
$(this).parent().fadeOut(500, function(){
$(this).remove();
});
event.stopPropagation();
});
$("input[type='text']").keypress(function(key){
if(key.which === 13){
var todoText = $(this).val();
$("ul").append("<li><span><i class='fas fa-trash-alt'></i></span> " + todoText + "</li>");
}
});
$("#form").click(function(){
$("input[type='text']").fadeToggle(150);
});
$(".novo").on("click", function(){
$(".container").append("<div class='grupa'><h1>To-Do List<span id='form'><i class='fas fa-edit'></i></span></h1><input type='text' placeholder='Add New Todo'><ul><li><span><i class='fas fa-trash-alt'></i></span> Sabah</li></ul></div>");
});
Thank You!!
You have to move your .on() bindings to a level higher up. That is because when you apply the .on() bindings to the <ul> element, the said element must be available in the DOM at runtime. That means that the newly added <ul>, triggered by clicking on the .novo button, will not have any JS events bounds to it.
In this case, you should move the binding to a parent element that is already present at runtime, e.g. the .container element. Refactoring your code, you can do this:
$(".container").on("click", ".grupa ul li", function(){
$(this).toggleClass("completed");
});
$(".container").on("click", ".grupa ul span", function(event){
$(this).parent().fadeOut(500, function(){
$(this).remove();
});
event.stopPropagation();
});

Changing bootstrap glyphicon onclick function

I'm trying to swap .glyphicon-menu-down to glyphicon-menu-up when user click on the link. What am I doing wrong? It's not working. Am I miss-using jquery?
Markup
<a data-toggle="collapse" data-parent="#accordion" href="#collapse1">
Admin
<span class="panelarrow glyphicon glyphicon-menu-down pull-right"></span></a>
Script
$(document).ready(function(){
$('.panelarrow').click(function(){
$(this).find('span').toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
});
});
In your case $(this) refers to .panelarrow and you are trying to find span element inside that .panelarrow.
Solution:
$(document).ready(function() {
$('.panelarrow').click(function(){
$(this).toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
});
});
Or if you want to change your icon by clicking on the a element use this:
$(document).ready(function() {
$('[data-toggle="collapse"]').click(function(){
$(this).find('span').toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
});
});
Clicking on the span (which includes the glyphicon) will let you use "this" to refer to the span - then the toggle classes can be included in the one command:
$(document).ready(function(){
$('.panelarrow').click(function(){
$(this).toggleClass('glyphicon-menu-down glyphicon-menu-up');
});
});

jQuery on click trouble

I am having trouble with my jQuery on click function. I can't figure out what I'm doing wrong since it isn't even registering the click in the console (I have set breakpoints and it refuses to visit my on click). I am using jQuery in other areas of my code, so I think I have linked it correctly, and I have checked the target several times to make sure that it is a class and I'm using the correct syntax, but I must have missed something. I feel like I have just been looking at it too long. Any help would be appreciated.
HTML:
<h3 class="collapseButton leftH3" data-toggle="collapse" data-target=".collapse_me">
Returns information about the current User
<span class="pull-right" id="arrow_me">
<i class="fa fa-arrow-down" aria-hidden="true"></i>
</span>
</h3>
JS:
function changeArrows() {
$('.collapseButton').on("click", function() {
$(this).next('.pull-right')
.html('<i class="fa fa-arrow-up" aria-hidden="true"></i>');
});
}
changeArrows();
You have to use children not next
function changeArrows() {
$('.collapseButton').on("click", function() {
$(this).children('.pull-right')
.html('<i class="fa fa-arrow-up" aria-hidden="true"></i>');
});
}
The on click is triggert but your selecotor is not correct.
$(this).children('.pull-right').html('<i class="fa fa-arrow-up" aria-hidden="true"></i>');
works fine for me (changed next for children)
Have you tried
$(document).ready(function(){
changeArrows();
});
Okay, rewrote it to do what you want it to do. Note that instead of next() (which gets the following sibling element with the given selector), you want children() (which gets the child elements of $(this)).
$(this) ends up resolving to be the h3 element in almost every case.
$(document).ready(function() {
$('.collapseButton').on('click', function(event) {
$(this).children('.pull-right')
.html('<i class="fa fa-arrow-up" aria-hidden="true"></i>');
});
});
Try putting the body of your function in $(document).ready( ... ). I don't think your event handler is available after this function is run. The .next() will also find the next sibling, but the element you're wanting to change is a child.
$(document).ready(function() {
$('.collapseButton').on("click", function() {
$(this).children('.fa.fa-arrow-up')
.html('<i class="fa fa-arrow-up" aria-hidden="true"></i>');
});
})
You can also just toggle the class for the i element without changing html:
$(".collapseButton").click(function(e) {
$(this).children('.pull-right').children('.fa-arrow-down').toggleClass('fa-arrow-up');
});
function setVisibility(id1,id2,id3) {
if(document.getElementById('bt1').value=='Show Box 3'){
document.getElementById('bt1').value = 'Show Box 4';
document.getElementById('bt1').value = 'Show Box 5';
document.getElementById(id1).style.display = 'inline';
document.getElementById(id2).style.display = 'none';
document.getElementById(id3).style.display = 'none';
}else{
document.getElementById('bt1').value = 'Show Box 3';
document.getElementById(id1).style.display = 'none';
document.getElementById(id2).style.display = 'inline';
document.getElementById(id3).style.display = 'inline';
}
}
<h4 class="pro_detail_title_name_new" >Product Description
<button type=button name=type id='bt1' onclick="setVisibility('sub3','sub4','sub5');";><span id="sub3" class="mobile-plus1"style="display:inline;" >+ </span><span id="sub5" class="fbutton"style="display:none;">-</span> </button></h4>
<div id="sub4"style="display:none;">-- inside --</div>

How to change a span's content when other element is clicked

I am looking to change the content of this span tag:
<span class="ui-btn-text" id="btnText">Read how we have helped</span>
To:
<span class="ui-btn-text" id="btnText">Hide Story</span>
This is what I got so far:
$('#storyBtn').click(function() {
$('#story-body').slideToggle('fast', function() {
$('#btnTextShow').hide();
$('#btnTextHide').show();
});
});
I think you just want to update the text of the span ... if so try this ->
<span class="ui-btn-text" id="btnText">Read how we have helped</span>
$('#storyBtn').click(function() {
$('#story-body').slideToggle('fast', function() {
$('#btnText').text("Hide Story");
$('#btnTextShow').hide();
$('#btnTextHide').show();
});
});
*Untested
Here is a great example on how to achieve this:
First look at the JSFiddle DEMO
Let's see what we have here:
$('.ui-btn-text:eq(1)').hide();
$('#storyBtn').click(function() {
$("#story-body").slideToggle(400);
$(".ui-btn-text").toggle(300);
});
And the html:
<div id="storyBtn">
<span class="ui-btn-text">Read how we have helped</span>
<span class="ui-btn-text">Hide Story</span>
</div>
<div id="story-body">
A long,...<br> long time ago...
</div>
INFO:
As you can see I simplified and removed all the unnecessary ID's and codes JUST TO MAKE VISIBLE HOW SIMPLE CAN ALL BE. You can redo this changes of mine.

Categories

Resources