Posts

Showing posts with the label Jquery

Are 301 Redirects Possible Using Javascript Or JQuery?

Answer : I know this is an old question but the answers don't really address the primary issue that was presented in the question which is a 301 redirect for SEO purposes (and the answer today may very well be different than it was when the question was originally asked and answered). The answer that no, you can't 301 redirect from the client is technically correct, however (and more importantly) you don't necessarily need to. While a true 301 would be preferred, in cases like this one where it's not possible (or transitioning away from hashbang URLs back to traditional URLs for example), the question is really whether or not there's a viable alternative that accomplishes the goal. Search Engine Land did a detailed test of Google's capabilities regarding JavaScript and this is the related excerpt from that article: JavaScript Redirects We first tested common JavaScript redirects, varying how the URL was represented in different ways. Th...

Chart Js 2 How To Set Bar Width

Answer : You were right : The attribute you have to edit is barPercentage . But maybe the error comes from where you edited the value. As you can see in the bar chart options : Name : barPercentage - Type : Number - Default : 0.9 - Description : Percent (0-1) of the available width each bar should be within the category percentage. 1.0 will take the whole category width and put the bars right next to each other. Read More The attribute is actually stored in scales.xAxes (" Options for xAxes " table). So you just have to edit your chart this way : var options = { scales: { xAxes: [{ barPercentage: 0.4 }] } } Here is a fully working example with a custom width ( 0.2 ) for the bar : var data = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", ...

.append VS .html VS .innerHTML Performance

Image
Answer : All three are slow to me. Modifying the dom on each iteration is slow. http://jsperf.com/jquery-append-vs-html-list-performance/24 I just added a new test in there: var html = []; for (var i = 0; i < len; i++) { html.push('<div>Test ' + i + '</div>'); } document.getElementById('list').innerHTML = html.join(''); This is much faster again. :) My method in Firefox does 26k Ops/sec vs 1,000, 10,000, and 13 That benchmark is worthless. innerHTML is always faster than DOM manipulation. jQuery seems faster because it prepares a string with all the HTML first while the others do one operation each iteration. Also note that jQuery.html() uses innerHTML whenever it can. jQuery from benchmark var html = ''; for (var i = 0; i < len; i++) { html += '<div>Test ' + i + '</div>'; } $('#list').html(html); innerHTML from benchmark var list = document.getElementById('l...

Auto-click Button Element On Page Load Using JQuery

Answer : You would simply use jQuery like so... <script> jQuery(function(){ jQuery('#modal').click(); }); </script> Use the click function to auto-click the #modal button JavaScript Pure: <script type="text/javascript"> document.getElementById("modal").click(); </script> JQuery: <script type="text/javascript"> $(document).ready(function(){ $("#modal").trigger('click'); }); </script> or <script type="text/javascript"> $(document).ready(function(){ $("#modal").click(); }); </script> Use the following code $("#modal").trigger('click');

AddID In JQuery?

Answer : ID is an attribute, you can set it with the attr function: $(element).attr('id', 'newID'); I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique. do you mean a method? $('div.foo').attr('id', 'foo123'); Just be careful that you don't set multiple elements to the same ID. Like this : var id = $('div.foo').attr('id'); $('div.foo').attr('id', id + ' id_adding'); get actual ID put actuel ID and add the new one

Ajax - JSON Doesnt Get Sent In PATCH Only

Answer : First, check that you use latest version of jQuery library: Older versions directly restrict unknown methods (PATCH is new one). I've tested on jQuery 1.7 - PATCH method working without problems. Second, not all browsers supports PATCH method using XMLHttpRequest: Like, IE 7,8 (9+ works okay) have XMLHttpRequest, but it throws an error on PATCH: new XMLHttpRequest().open('PATCH', '/'); //Illegal argument To fix this, you may force jQuery to use the old proprietary ActiveXObject xhr, like so: $.ajax({ url : 'http://127.0.0.1:8001/api/v1/pulse/7/', data : data, type : 'PATCH', contentType : 'application/json', xhr: function() { return window.XMLHttpRequest == null || new window.XMLHttpRequest().addEventListener == null ? new window.ActiveXObject("Microsoft.XMLHTTP") : $.ajaxSettings.xhr(); } }); A bit late, but this worked for me when I got...

Asynchronously Updating A Bootstrap Progress Bar With JQuery's $.ajax

Answer : aren't you dividing by zero here when host = 0 in the for loop? updateProgress(100/host); you can use a variable hosts to keep track of the number of hosts you have.Then the progress will be as below. var hosts = 23;// total number of hosts updateProgress((host/hosts)*100); The other thing is the ajax you're firing is asynchronous, so what's happening is it fires and doesn't wait for the results. You can either "scan" each host serially one at a time updating the progress bar or scan all of them simultaneously having the progress bar update as the asynch results come back. Can you specify which behavior you're trying to achieve? [UPDATE] toggle async flag in the ajax call below for what you want. function updateProgress(percentage){ if(percentage > 100) percentage = 100; $('#progressBar').css('width', percentage+'%'); $('#progressBar').html(percentage+'%'); } var hosts = 23; va...

Bootstrap-select Add Item And Select It

Answer : You have a typo. Instead of: $('#myselect').append('<option val="'+newitemnum+'">'+newitemdesc+'</option>'); You need: $('#myselect').append('<option value="'+newitemnum+'">'+newitemdesc+'</option>'); Here is a JSFiddle demo: http://jsfiddle.net/xbr5agqt/ The "Add and select 'Soy Sauce' option" button does the following: $("#myselect").append('<option value="'+newitemnum+'">'+newitemdesc+'</option>'); $("#myselect").val(4); $("#myselect").selectpicker("refresh"); One slightly faster approach (used by the "Add and select 'Relish' option" button) is to append the new <option> element with the selected attribute already applied: $("#myselect").append('<option value="'+newitemnum+'" selected=...

Autoclose Alert

Answer : jsFiddle Demo This functionality is not possible with an alert. However, you could use a div function tempAlert(msg,duration) { var el = document.createElement("div"); el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;"); el.innerHTML = msg; setTimeout(function(){ el.parentNode.removeChild(el); },duration); document.body.appendChild(el); } Use this like this: tempAlert("close",1000); You can't close alert any how . But you can use div To show your alert MSG. function Mymsg(msg,duration) { var alt = document.createElement("div"); alt.setAttribute("style","position:absolute;top:50%;left:50%;background-color:white;"); alt.innerHTML = msg; setTimeout(function(){ alt.parentNode.removeChild(alt); },duration); document.body.appendChild(alt); } You can use as : Mymsg('close',2000) jsFiddle Demo Basically you...

Adding Data Attribute To DOM

Answer : Use the .data() method: $('div').data('info', '222'); Note that this doesn't create an actual data-info attribute. If you need to create the attribute, use .attr() : $('div').attr('data-info', '222'); jQuery's .data() does a couple things but it doesn't add the data to the DOM as an attribute. When using it to grab a data attribute, the first thing it does is create a jQuery data object and sets the object's value to the data attribute. After that, it's essentially decoupled from the data attribute. Example: <div data-foo="bar"></div> If you grabbed the value of the attribute using .data('foo') , it would return "bar" as you would expect. If you then change the attribute using .attr('data-foo', 'blah') and then later use .data('foo') to grab the value, it would return "bar" even though the DOM says data-foo="blah...

Bootstrap Toast Does Not Show Up

Answer : You need to put the valid option. i:e show, hide or a callback function . See - https://getbootstrap.com/docs/4.2/components/toasts/. $('.toast').toast('show'); <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <div class="toast" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <img height="200px" width="200px" src="https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg" class="rounded mr-2" alt="..."> <strong class="mr-auto">Boots...

AngularJS : Ng-model Binding Not Updating When Changed With JQuery

Answer : Angular doesn't know about that change. For this you should call $scope.$digest() or make the change inside of $scope.$apply() : $scope.$apply(function() { // every changes goes here $('#selectedDueDate').val(dateText); }); See this to better understand dirty-checking UPDATE : Here is an example Just use; $('#selectedDueDate').val(dateText).trigger('input'); I have found that if you don't put the variable directly against the scope it updates more reliably. Try using some "dateObj.selectedDate" and in the controller add the selectedDate to a dateObj object as so: $scope.dateObj = {selectedDate: new Date()} This worked for me.

Animating AddClass/removeClass With JQuery

Answer : Since you are not worried about IE, why not just use css transitions to provide the animation and jQuery to change the classes. Live example: http://jsfiddle.net/tw16/JfK6N/ #someDiv{ -webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease; -o-transition: all 0.5s ease; transition: all 0.5s ease; } Another solution (but it requires jQueryUI as pointed out by Richard Neil Ilagan in comments) :- addClass, removeClass and toggleClass also accepts a second argument; the time duration to go from one state to the other. $(this).addClass('abc',1000); See jsfiddle:- http://jsfiddle.net/6hvZT/1/ You could use jquery ui's switchClass , Heres an example: $( "selector" ).switchClass( "oldClass", "newClass", 1000, "easeInOutQuad" ); Or see this jsfiddle.

Append Before Last Child

Answer : You could use .before() to add a sibling before the element: $("#wrapper .content:last").before('<div class="content"><div class="subcontent">Third</div></div>'); .insertBefore() does the same thing with a different syntax, namely that you select the element to be added, and pass the element you want to add it before. $("#wrapper .content:last").before('<div class="content"><div class="subcontent">Third</div></div>'); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="wrapper"> <div class="content"> <div class="subcontent"> First </div> </div> <div class="content"> <div class="subcontent"> Second </div> ...

Call Function With SetInterval In JQuery?

Answer : To write the best code, you "should" use the latter approach, with a function reference: var refreshId = setInterval(function() {}, 5000); or function test() {} var refreshId = setInterval(test, 5000); but your approach of function test() {} var refreshId = setInterval("test()", 5000); is basically valid, too (as long as test() is global). Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library. First of all: Yes you can mix jQuery with common JS :) Best way to build up an intervall call of a function is to use setTimeout methode: For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this: function test(){ console.log('test called'); setTimeout(test, 5000); } Finally you have to trigger the function once: $(document).re...

Bootstrap Dropdown Not Opening First Click On React 16

Answer : You may have jQuery or Bootstrap included twice. I don't use React, but I was having the same problem with Angular. It turns out that I was including jQuery/Bootstrap in my index.html as well my "scripts" configuration (which I think would be your "entry"). You should import this line and Test again : import 'bootstrap/dist/js/bootstrap.bundle'; this work for me like a charm :) I got the same issue. I noticed that when i was using bootstrap.min.js and jquery.min.js at a same time. Then my dropdown takes two click for toggle in first time after page load. Then i commented bootstrap.min.js . Now it is not giving me this issue. Try this. Maybe it will solve your problem.

Bootstrap Shown.bs.tab Event Not Working

Answer : Bootstrap tab events are based off the .nav-tabs elements, not the .tab-content elements. So in order to tap into the show event, you need the element with an href that is pointed towards #tab1 , not the #tab1 content element itself. So instead of this: $('#tab1').on('shown.bs.tab', function (e) { console.log("tab1"); }); Do this instead: $('[href=#tab1]').on('shown.bs.tab', function (e) { console.log("tab1"); }); Or, to capture all of them, just do this: $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { console.log(e.target.href); }) Demo in Stack Snippets $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { console.log(e.target.href); }) <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/> <script src="//cdnjs.cloudflare.com/ajax/li...

Bootstrap 3 Popover Arrow And Box Positioning

Answer : You can customize the placement of the popover or it's arrow my manipulating the .popover CSS once the popover is shown. For example, this pushes the top of the popover down 22 pixels.. $('[data-toggle=popover]').on('shown.bs.popover', function () { $('.popover').css('top',parseInt($('.popover').css('top')) + 22 + 'px') }) Working demo : http://bootply.com/88325 I recommend using the placement method rather than the shown.bs.popover event. This will not trigger a popover jump when the element is shown. This is how it works: $('[data-toggle=popover]').popover({ placement: function(context, source) { var self = this; setTimeout(function() { self.$arrow.css('top', 55); self.$tip.css('top', -45); }, 0); return 'right'; }, }); My use case is that the popover placement is top and I have to remove the arrow. I followed the solution provide...

Adjust Bootstrap Tooltip Width

Answer : I hope I'm not too late to post this for future programmers looking for answers. There's a question like this one. Go to this link: How do you change the width and height of Twitter Bootstrap's tooltips? One of the answers there is very useful. It was answered by @knobli. I don't know how to link the answer but I hope you can go to that page and vote it up. Anyway, I'll just copy it right here. For CSS: .tooltip-inner { max-width: 100% !important; } For HTML: <a href="#" data-toggle="tooltip" data-placement="right" data-container="body" title="" data-original-title="Insert Title">Insert Title</a> Just add data-container="body" and you're ready to go.

Bootstrap 4 File Input

Answer : Updated 2021 Bootstrap 5 Custom file input no longer exists so to change Choose file... you'd need to use JS or some CSS like this. Bootstrap 4.4 Displaying the selected filename can also be done with plain JavaScript. Here's an example that assumes the standard custom-file-input with label that is the next sibling element to the input... document.querySelector('.custom-file-input').addEventListener('change',function(e){ var fileName = document.getElementById("myInput").files[0].name; var nextSibling = e.target.nextElementSibling nextSibling.innerText = fileName }) https://codeply.com/p/LtpNZllird Bootstrap 4.1+ Now in Bootstrap 4.1 the "Choose file..." placeholder text is set in the custom-file-label : <div class="custom-file" id="customFile" lang="es"> <input type="file" class="custom-file-input" id="exampleInputFile" aria-describedby=...