I'm trying to build a page which will have a scrolling list of Twitter search results (using twitter.search for jQuery). The user should be able to change the search term by clicking a button (so, clicking "Apple" will change the search term to "Apple".
I'm using a variable to set the search term. Setting that variable to a text string (i.e. searchText = "Pineapple";) works. But when I try to change the variable using the buttons, nothing happens.
//edit - the button doesn't seem to change the variable. Thoughts? Thanks.
<script type="text/javascript">
//set default value for searchText
searchText = "Pineapple";
//this sets up our Twitter stream
$(document).ready(function() {
$('#twitter-stream').twitterSearch({
term: searchText,
// no fade
animOut: { opacity: 1 },
avatar: false,
anchors: false,
bird: false,
colorExterior: 'white',
colorInterior: 'white',
pause: true,
time: false,
timeout: 2000
});
});
</script>
<script type="text/javascript">
$("#button-container").on("button", "click", function( e ) {
searchText = $(this).text();
});
</script>
<div id="twitter-stream" title="Mouse away to un-pause">
</div>
<div id="button-container">
<button class="button"> Apple </button>
</div>
<button onclick="alert(searchText);">Click me!
</button>
This code is very inefficient, you can use jQuery to define one function that handles all click events for the buttons, as opposed to 4 nearly identical functions.
Delegate your events using jQuery's .on:
$("#someContainerDiv").on("button", "click", function( e ) {
searchText = $(this).text();
});
This eliminates the need for an array of values, as you just take the innerText of the button itself.
References
Here is some info on jQuery's on and here is some info on the delegate function it replaces.
Related
I'm using Infinite Ajax Scroll for pagination on my blog. When there are no more posts left to load, I want to hide the trigger (the buttons) parent container (currently, it just has opacity: 0, but this leaves unwanted whitespace).
In the console, I can see that IAS leaves a message saying "No more pages left to load", so I know there is a method in place to check if more posts exist. But, having applied two methods, I cannot get it to work.
Method 1: Using last:function()
Method 2: Checking if the trigger has opacity: 0, then hiding parent container if so
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/#webcreate/infinite-ajax-scroll#3.0.0-beta.6/dist/infinite-ajax-scroll.min.js"></script>
<div class="container pagination-hide">
<div class="row">
<div class="col-12">
<div class="pagination">
<a class="loadmore">Load more</a>
</div>
</div>
</div>
</div>
<script>
$(function() {
var ias = new InfiniteAjaxScroll('.insertPosts', {
item: '.insertCard',
pagination: '.blog-pagination',
next: '.next-posts-link',
trigger: '.loadmore',
loadOnScroll: false,
last:function(){
$(".pagination-hide").addClass("d-none");
}
});
// $('.loadmore').click(function(){
// if ( $(this).css('opacity') == '0' ) {
// console.log("true");
// $(this).parent(".pagination-hide").addClass("d-none");
// }
// });
});
</script>
Have also tried the following, as per IAS docs, however, this just adds the d-none class to pagination-hide on page load, rather than adding the class (as it should) if there are no more posts to load.
trigger: {
element: '.loadmore',
// this function is called when the button has to be hidden
hide: function(element) {
$(element).closest(".pagination-hide").addClass("d-none");
element.style.opacity = '0'; // default behaviour
}
},
Seems like you would also need to add a show() method that un-does the changes in hide(), in order to get the correct behavior:
trigger: {
element: '.loadmore',
// this function is called when the button has to be hidden
hide: function(element) {
$(element).closest(".pagination-hide").addClass("d-none");
element.style.opacity = '0'; // default behaviour
},
show: function(element) {
$(element).closest(".pagination-hide").removeClass("d-none");
element.style.opacity = '1';
}
},
Sorry, but you went on a bad road. You shoud show button <a class="loadmore">Load more</a> if you have some other conten unstead of hiding unnecessary. It's wrong in root. You are calling unnecessary operations in the DOM render. You better rewrite your code.
AFAICT you were on the right track with your first attempt - the last event seems like exaclty the right way to do what you need. But the docs also show that you need to bind event handlers with .on(), not pass them as options, which is what you tried.
For example, something like this:
var ias = new InfiniteAjaxScroll('.insertPosts', {
// ... your options
// last:function(){} // <-- won't work, not the way to bind event handlers
});
// What we want to happen when we've hit the last page
function noMorePages() {
$(".pagination-hide").addClass("d-none");
}
// Handle the "last" event with our function
ias.on('last', noMorePages);
There is a similar example in the docs.
You simply need to provide show and hide functions for the trigger ref. The library calls the functions automatically on last event.
Demo website https://zyf5k.csb.app/
Codesandbox https://codesandbox.io/s/zen-volhard-zyf5k?file=/index.js
Code for ready reference:
window.ias = new InfiniteAjaxScroll(".container", {
item: ".item",
next: nextHandler,
trigger: {
element: ".loadmore",
show: function (element) {
element.parentElement.style.display = "block";
},
hide: function (element) {
//hide desired element`
element.parentElement.style.display = "none";
}
}
});
Note: Didn't realize #Kevin had already answered this. Posting the answer for extra info.
I'm looking for a way to show/hide divs based on the jQuery autocomplete search results.
This is the autocomplete function I have:
$('#catalogSearch .searchBox').mouseup(function (e) { e.preventDefault(); }).autocomplete({
source: services,
autoFill: true,
minChars: 0,
focus: function (event, ui) {
event.preventDefault(); // Prevent ui.item.value from showing up
$('#catalogSearch .searchBox').val(ui.item.label);
return false;
},
select: function (event, ui) { // Triggered when an item is selected from the menu?
$('#catalogSearch .searchBox').val(ui.item.label);
window.location.href = ui.item.value.find("a").attr("href");
return false;
},
open: function () { $('.ui-menu').css('max-width', '100%') }
})
The source 'services' is just an array of objects with label & value. Basically, I want to filter out my divs based on the autocomplete results (the list that shows up on .ui-menu-item) as shown here:
before & after
(In case if the images don't work)
My html looks like this:
<div id="catalogSearch">
...
<input type="text" class="searchBox ui-autocomplete-input ...>
<input id="catalogSearchSubmit" class="searchSubmit" type="submit">
...
</div>
<div class="row">
...
<div id="product-apple">...</div>
<div id="product-banana">...</div>
<div id="product-cherry">...</div>
<div id="product-melon">...</div>
<div id="product-pineapple">...</div>
<div id="product-kiwi">...</div>
...
</div>
And basically, I want to use this filtering function (or something like this):
var filterResults = function () {
var results = $('.ui-menu-item');
$('.product-list.item').hide();
results.each(function (r) {
$('#product-' + $(this).text()).show();
});
};
and show only relevant divs. For example, if I search "pl", I would only want to see div "apple", "pineapple" & "plum." I tried to add it as a part of the search event but seems it doesn't work. Is there any way I can do it within the autocomplete scope?
Thank you for your answer in advance!
What I would do is something like this :
function search(value){
//$(elems) == your divs selector
$(elems).hide();
$(elems).each(function(){
if($(this).html().match(value)){
$(this).show();
}
});
}
You can get read rid of your divs id.
Then use this search function inside jq autocomplete focus and/or select and give it ui.item.label value, which might be the value you're looking for.
Note : As all your possible results are already loaded on page, I don't see the point of autocomp as you can get this search function to work instantly like this
$('.searchBox').keyup(function(){ search( $(this).val() ) }
I need to have multiple buttons on page (created through a PHP loop) - there's not fixed number of buttons as there'll be one for each record displayed. I'd like to get the value of that button with javascript when it is clicked.
So far the html looks like:
<button id="update[0]" value="test">Update</button>
<button id="update[1]" value="test">Update</button>
<button id="update[2]" value="test">Update</button>
etc....
and my script is:
$(document).ready("#update").click(function() {
var updateId = $("#update").val
alert(updateId);
});
So far the script detects when any #update[] button is clicked but how do I know the index of the particular button in order to get the value (i.e. if #update[38] is clicked how do I know it's #update[38] so I can find the value of that particular button?
Thanks.
You do not want to chain off the document ready like you are as its returning the document.
$(document).ready("#update").click(function() {
So you are capturing the document.click not not button.click so when you reference $(this).val() you will get document.value which does not exist.
Should be:
$(document).ready(function () {
$("button").click(function () {
//no reason to create a jQuery object just use this.value
var updateId = this.value;
alert(updateId);
});
});
http://jsfiddle.net/SeanWessell/2Lf6c3fx/
Use the "this" key word.
$(document).ready("#update").click(function() {
var updateId = $(this).val();
alert(updateId);
});
The this keyword in javascript allows you to reference the particular instance of the object you are interacting with.
Also, add "()" to the end of val.
I believe you meant to use
var updateId = $("#update").val()
With jQuery you can use $(this).val()
You could also get the text of the button using .text()
With pure Javascript you could use .value if the button has a value attribute
See this: Javascript Get Element Value
I would suggest the following
<button id="0" class="updatebutton" value="test">Update</button>
<button id="1" class="updatebutton" value="test">Update</button>
<button id="2" class="updatebutton" value="test">Update</button>
Use a class to apply your click function.
$(document).ready(function () {
$("updatebutton").click(function () {
var updateId = this.id;
alert(updateId);
});
});
And use the id to specify the index of the button.
The trick is to give all your buttons the same class and then use $(this) to find out which button was clicked.
Once you know the button, then you can check for any of its attributes like id, value or name.
$(function() {
$(".xx").on("click", function(evt) {
var clicked_button = $(this);
alert(clicked_button.attr("value"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="update_1" class="xx" value="test1">Button 1</button>
<button id="update_2" class="xx" value="test2">Button 2</button>
<button id="update_3" class="xx" value="test3">Button 3</button>
Hi there a few things wrong with your javascript there.
You are attaching onClick to the document! The function ready returns the document.
Wrong:
$(document).ready("#update").click(function() {
Right:
$(document).ready(function () { $(valid_selector).click...
You are attempting to refetch the button with $('#update'), which 1 doesn't fetch anything, and two if it did would return all of the buttons. So use $(this) in the scope of the click function instead to refer to the button clicked.
Here is your javascript corrected:
https://jsfiddle.net/ffkekpmh/
//When the document is ready call this function
$(document).ready(function () {
//Select all buttons whoes id starts with update
//https://api.jquery.com/category/selectors/attribute-selectors/
$('button[id^="update"]').click(function() {
//Store the id attribute from the clicked button
var updateId = $(this).attr("id");
//Store the value attribute from the clicked button
var value = $(this).attr("value");
alert("You clicked button:"+updateId+" with value: "+value);
});
});
I want to pass the value of the limit in Jquery at the touch of a button. I almost found a solution, but can not quite understand. How to set the value to "limit:" the default and change it by pressing the button.
HTML
<button id="pagelimit default">1</button>
<button id="pagelimit">2</button>
<button id="pagelimit">3</button>
</div>
JS
function displayVals() {
var pagelim = $( "#pagelimit" ).val();
};
$('#product-grid').mixItUp({
pagination: {
limit: $pagelim // insert button value
}
});
Please help me solve this problem.
ID of an element must be unique... It looks like you want to update the limit option with the clicked button's text so
<button class="pagelimit default">1</button>
<button class="pagelimit">2</button>
<button class="pagelimit">3</button>
then
//this method is not used in the below code as we don't know which button was clicked here... if you share how the `displayVals` method is called then we can try to make this work
function displayVals() {
var pagelim = $("#pagelimit").val();
};
jQuery(function ($) {
$('.pagelimit').click(function () {
//update the limit option
$('#product-grid').mixItUp('setOptions', {
limit: +$(this).text()
});
});
//initialize the plugin
$('#product-grid').mixItUp({
pagination: {
limit: 1
}
});
})
Goal
I've got a web page with a table of items. Each item has a delete button beside it. When that button is clicked, I want to
Ask the user to confirm
Delete the corresponding item from the database
Remove that item's row from the list
Current solution
Right now, I'm doing something like this:
$('button.delete').click(function(){
thisRow = $(this).parent();
itemID = $(this).parent().attr('id');
if (confirm('Are you sure?')){
$.post('/manage_items.php', {"action":"delete", "itemid":itemID}, function(){
thisRow.hide("slow").remove();
});
}
}
This solution works because each button.delete can determine which row and item it belongs to, and act accordingly.
Desired solution
Instead of the clunky "OK or Cancel" alert box, I'd like to use a jQuery UI dialog box. But I'm not sure how to let the dialog know which row and item it should handle on any given click.
Here's how you set it up:
1) Define a dialog box div
<div class="dialogbox" id="confirmdeleteitem" title="Really DELETE this item?">
<p>Gee golly, are you s-s-s-sure you want to do that?!</p>
</div>
2) Set up the dialog box behavior
$('#cofirmdeleteitem').dialog({
//other options - not relevant here
buttons: {
"Nevermind": function() {
//do nothing
},
"Alright! Woo!": function(){
//do something
}
}
});
3) Set the click event that will open the dialog
$('button.delete').click(function(){
$('#confirmdeleteitem').dialog('open');
});
In this last step, I'd like to be able to pass some information to the dialog - which delete button was clicked, for example. But I don't see a way to do that.
I could insert a hidden dialog div.dialog into each item row up front, or insert one into a particular row after its button is clicked. Then the $(this).parent() references would grab the correct row...
Is there an easier way to do this?
i do something like this:
function ConfirmationDialog(title, question, options) {
var d = $('<div title="' + title + '"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + question + '</p></div>');
d.dialog({
bgiframe: true,
resizable: false,
height: 190,
width: 350,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
buttons: options
});
}
and then call my function from the click event.
It ended up being most straightforward to set up the dialog behavior inside the click function itself. Actually, it's not much different than my original example.
$('button.delete').click(function(){
thisRow = $(this).parent().parent();
thisRow.css("background-color","red");
skuid = $(this).parent().parent('tr').attr('id').substr(5);
$('#dialogbox').dialog({
autoOpen: false,
modal: true,
draggable: true,
width: 600,
buttons: {
"Actually, I can just mark it inactive": function() {
thisRow.css("background-color","inherit");
$(this).dialog("close");
},
"This SKU needs to be deleted": function() {
$.post('/intranet/backstage/modify_sku_info.php', {"action":"delete", "skuid":skuid}, function(result){
thisRow.hide("slow").remove();
});
$(this).dialog("close");
}
}
});
$('#dialogbox').dialog('open');
return false;
});
Since div#dialogbox doesn't get hidden until $('#dialogbox').dialog() is called, I just gave it an inline style of display:none.
If I end up needing something that can be generalized, as hyun suggested, I'll revisit the issue.
You could store the row in a global variable, like this:
var deletingId;
$('button.delete').click(function() {
deletingId = $(this).parent().attr('id');
$('#confirmdeleteitem').dialog('open');
});
$('#confirmdeleteitem').dialog({
//other options - not relevant here
buttons: {
"Never mind": function() { },
"Alright! Woo!": function(){
$.post(
'/manage_items.php',
{ action: "delete", itemid: deletingId },
function() {
$('#' + deletingId).hide("slow").remove();
}
);
}
}
});
This will only work if the dialog is modal; otherwise, the user could click two different delete links, and you'd need multiple dialogs.
Why can't you just call a setup method to build the dialog as you see fit?
setupMyDialog( '#confirmdeleteitem', info1, info2 );
$('#confirmdeleteitem').dialog...
Alternatively, just store the information in global space before you show the dialog. Remember that your javascript variables can have global scope, or you can store information arbitrarily on objects/functions (which are just objects).
myDataStore = {};
myDataStore.row = foo;
myDataStore.col = bar;
You could add the "rel" attribute to the dialog and store it there, instead. That way you don't need to worry about global variables, and it's semantically not-too-bad, since you are defining a relationship between the dialog and a row. So it'd just be $('#confirmdeleteitem').attr('rel', $(this).parent().attr('id').dialog('open');