Javascript handling multiple IDs - php

I'm completely new in javascript. The problem is, I have multiple textarea and div which 'echo'-ed out via PHP with ID (for example textarea_1,textarea_2...), and I wanna do something like, when the textarea is on focus, only that particular textarea which being focussed will slide down and expand.
Html
<textarea id="comment_textarea_1"></textarea>
<div id="button_block_1"><button type="submit">Submit</button><button type="submit" id="cancel_1">Cancel</button></div>
<textarea id="comment_textarea_2"></textarea>
<div id="button_block_2"><button type="submit">Submit</button><button type="submit" id="cancel_2">Cancel</button></div>
Javascript
$(document).ready(function () {
var $this = $(this);
var $textareaID = $this.attr("id").replace("comment_textarea_");
var $buttonblockID = $this.attr("id").replace("button_block_");
var $cancelID = $this.attr("id").replace("cancel_");
var $textarea = $('#'+$(textareaID));
var $button = $('#'+$(buttonblockID));
var $cancel = $('#'+$(cancelID));
$textarea.focus(function(){
$textarea.animate({"height": "85px",}, "fast" );
$button.slideDown("fast");
return false;
});
$cancel.click(function(){
$textarea.animate({"height": "18px",}, "fast" );
$button.slideUp("fast");
return false;
});
});
Thank you!

I explained it in the code. Try this.
$(document).ready(function () {
// select all the textareas which have an id starting with 'comment_textarea'
var $textareas = $("textarea[id^='comment_textarea']");
$textareas.on("focus",function(){
// now $(this) has the focused element
$(this).animate({"height": "85px",}, "fast" );
// find the button block of this div and animate it
$("div[id^='button_block']",$(this)).slideDown("fast");
});
$textareas.on("focusout",function(){
// now $(this) has the focused out element
$(this).animate({"height": "18px",}, "fast" );
// find the button block of this div and animate it
$("div[id^='button_block']",$(this)).slideUp("fast");
});
});

I believe I understand what you're attempting. Please let me know if the following is the effect you're after:
$("[id^='comment_textarea_']").on({
focus: function(){
$(this).stop().animate({ height: '85px' }, 750).next().slideDown();
},
blur: function(){
$(this).stop().animate({ height: '20px' }, 250).next().slideUp();
}
});​
Fiddle: http://jsfiddle.net/pwype/2/

I'm confused. The above answers are concentrating on using ID's... The last time I checked this is one of the main reasons we have the class attribute?
For example:
$(document).ready(function()
{
$('.comment-textarea').focus(function()
{
$(this).animate(
{
'height' : '85px'
}, 'fast');
$(this).next('.button-block').slideDown('fast');
}).blur(function()
{
$(this).animate(
{
'height' : '18px'
}, 'fast');
$(this).next('.button-block').slideUp('fast');
});
});
And the HTML:
<textarea id="comment_textarea_1" class="comment-textarea"></textarea>
<div id="button_block_1" class="button-block"><button type="submit">Submit</button><button type="submit" id="cancel_1">Cancel</button></div>
<textarea id="comment_textarea_2" class="comment-textarea"></textarea>
<div id="button_block_2" class="button-block"><button type="submit">Submit</button><button type="submit" id="cancel_2">Cancel</button></div>
And a little fiddle to show it working:
http://jsfiddle.net/ngYMh/

Related

Suggestion box not showing for nearest input

I cannot seem to get my suggestion box to show for the nearest input after adding more inputs dynamically.
The below code is where I am currently, I can see the suggestion box for a new input and add to that new input but if I go back to edit the input data the suggestion box fails to show.
<div id="tester"></div>
<button id="add_test">ADD</button>
$(document).ready(function() {
$("#add_test").on("click", function() {
var input = '<div class="flavhey"><div class="flavourInput"><input class="ftext form-control flavour-name-input" type="text" name="flav-name-input" value="" placeholder="Flavour Name" /><div class="suggestion-box"></div></div></div>';
$('#tester').append(input);
});
$(document).on('keyup', '.flavhey input', function(e){
var token = '<?php echo json_encode($token); ?>';
var search = $(this).val();
$.ajax({
type: "POST",
url: "controllers/recipeControl.php",
data: { token: token, search: search },
beforeSend: function(){
$(".flavour-name-input").css("background","#FFF no-repeat 165px");
$(".suggestion-box").css("background","#FFF no-repeat 165px");
},
success: function(data){
$('.flavhey input').closest('flavourInput input').next('.suggestion-box').show();
$('.flavhey input').next('.suggestion-box').html(data);
$(".suggestion-box").css("background","#FFF");
}
});
return false;
});
$(document).on("click",".search-flavour",function(e) {
e.preventDefault();
$(this).closest('.flavourInput').find('.flavour-name-input').val($(this).text());
$('.suggestion-box').hide();
return false;
if(isset($_POST['search'])) {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& json_decode($_POST['token']) === $_SESSION['token']){
$search = $_POST['search'];
$html = '<ul>';
$content = $flavours->getAllFlavoursSearch($search);
foreach ($content as $con) {
$html .= '<li class="search-flavour"><b>'.$con['flavour_name'].'</b> - <i>'.$con['flavour_company_name'].'</i></li>';
}
$html .= '</ul>';
echo $html;
}
}
Ok short version:
Use var box = $(e.target).next(".suggestion-box"); to aquire a reference to the correct suggestion box in the success handler of the ajax request.
Long version:
I replaced the php parts with static placeholders to get a runnable example.
$(document).ready(function() {
$("#add_test").on("click", function() {
var input = '<div class="flavhey"><div class="flavourInput"><input class="ftext form-control flavour-name-input" type="text" name="flav-name-input" value="" placeholder="Flavour Name" /><div class="suggestion-box"></div></div></div>';
$('#tester').append(input);
});
$(document).on('keyup', '.flavhey input', function(e) {
var token = "[token]";
var search = $(this).val();
var box = $(e.target).next(".suggestion-box");
box.show();
box.html("TestData");
box.css("background", "#FFF");
return false;
});
$(document).on("click", ".search-flavour", function(e) {
e.preventDefault();
$(this).closest('.flavourInput').find('.flavour-name-input').val($(this).text());
$('.suggestion-box').hide();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tester"></div>
<button id="add_test">ADD</button>
<ul>
<li class="search-flavour">
<b>flavour_name_1</b> - <i>flavour_company_name_1</i>
</li>
<li class="search-flavour">
<b>flavour_name_2</b> - <i>flavour_company_name_2</i>
</li>
<li class="search-flavour">
<b>flavour_name_3</b> - <i>flavour_company_name_3</i>
</li>
</ul>
Now being able to execute your code I was able to reproduce the described error. Please try to provide a runnable example next time.
I realized that your box was only appearing once because the call to .show() wasn't working at all. It was visible from the beginning just without any content so you couldn't see it, then after setting html() it had content and it looked like the call to show() worked as intended.
Afer you clicked on a .search-flavour all boxes were correctly hidden and thus never appeared again.
So to fix this, replace the success handler of the ajax request with this:
success: function(data){
// e.target is the currently active input element
var box = $(e.target).next(".suggestion-box");
box.show()
.html(data)
.css("background", "#FFF");
}

tinymce on textarea generated by php/jquery post

I have tinymce working well FIRST time you click the button, but after that it doesn't init anymore, no errors however.
To get editor again you need to refresh page.
Is it possible to get init editor to the text area every time you open the modal without refreshing page ?
$(document).ready(function() {
$(document).on('click', '.btn.modal', function() {
var title = $('.modal-title'),
content = $('.modal-body'),
footer = $('.modal-footer');
$.post('units.php', { addnew: 'unit' }, function(r) {
title.html(r.title);
content.html(r.content);
footer.html(r.btns);
tinymce.init({ selector: 'textarea' });
$('#modal').modal('show');
},'json');
});
});
The problem is you are using the general initialisating, which probably conflits with the textarea(s) which already have been initialised... .
The best way to solve this is by destroying all the initialised tinymce first using:
$('textarea').tinymce().re‌​move();
and then initialising them again like this:
tinymce.init({ selector: 'textarea' });
In your example this would be:
$(document).ready(function() {
$(document).on('click', '.btn.modal', function() {
var title = $('.modal-title'),
content = $('.modal-body'),
footer = $('.modal-footer');
$.post('units.php', { addnew: 'unit' }, function(r) {
title.html(r.title);
content.html(r.content);
footer.html(r.btns);
$('textarea').tinymce().re‌​move();
tinymce.init({ selector: 'textarea' });
$('#modal').modal('show');
},'json');
});
});

Pull Down To Refresh (Div)

The Question
How could I make it where when you pull <div id="content"> down, it does a function and shows a div at the top of the screen that says "Pull Down To Refresh"?
I know iScroll does this, but it won't work with what I'm trying to do. It only works with UL's.
Here is my HTML
<div id="pullDown">
<span class="pullDownIcon"></span><span class="pullDownLabel">Pull down to refresh...
</span>
</div>
<div id="content">
(There is a bunch of items that are loaded in via jquery and php, when you pull down to refresh, I want it to basically react that function.)
</div>
<script>
$(function() {
var refreshCallback = function(loader) {
setTimeout(function(){
//loader.finish();
}, 1000);
};
var cancelRefreshing = function() {
};
$("#draggable").pulltorefresh({
async: true,
// event triggered when refreshing start
refresh: function(event, finishCallback) {
element = $(this)
setTimeout(function(){
alert("refresh");
// you must call this function if refreshing process runs asynchronusly
finishCallback();
}, 1000);
},
abort: function() {
alert("abort");
}
});
});
</script>
for full Demo Click Here
You can provide with iScroll plugin.
iScroll 4: http://cubiq.org/iscroll-4
Github Page: https://github.com/cubiq/iscroll
Demo: http://cubiq.org/dropbox/iscroll4/examples/pull-to-refresh/
try this
$( "#pullDown" ).on( "dragstart", function( event, ui ) {} );
inside the function u can have the ajax call to load the content
$("#content").load("<something.php>");
that is on the whole
$( "#pullDown" ).on( "dragstart", function() {
$("#content").load("<something.php>");
} );

Play a certain audio track when clicked

All the songs have a .song class but it plays the first song on the playlist. It's basically the play button for the whole playlist. I've play around with this for awhile and I can't seem to get it right. It might be the simplest thing too. I have the song populate with php depending on the album. I want people to be able to click a certain song and that song plays.
example: http://mixtapemonkey.com/mixtape?m=637
Also if you know how to toggle between the play and stop button, that would be nice to throw in there too. Thanks!
<script>
jQuery(document).ready(function(){
i=0;
nowPlaying = document.getElementsByClassName('playsong');
nowPlaying[i].load();
$('.play').on('click', function() {
nowPlaying[i].play();
callMeta();
});
$('.song').on('click', function() {
nowPlaying[i].play();
callMeta();
});
$('.pause').on('click', function() {
nowPlaying[i].pause();
callMeta();
});
$('.next').on('click', function() {
$.each($('audio.playsong'), function(){
this.pause();
});
++i;
nowPlaying[i].load();
nowPlaying[i].play();
callMeta();
})
function callMeta(){
var trackTitle = $(nowPlaying[i]).attr('data-songtitle');
$('.songtitle').html(trackTitle);
var trackArtist = $(nowPlaying[i]).attr('data-songartist');
$('.songartist').html(trackArtist);
}
})
You have to target the audio element inside each .song, now you're always targeting the first one.
To toggle, check if the audio is paused, and play() or pause() accordingly :
$('.song').on('click', function() {
var audio = $('.playsong', this).get(0);
if (audio.paused) {
audio.play();
}else{
audio.pause()
}
callMeta();
});
EDIT:
with a few changes, I'm guessing something like this would work :
jQuery(document).ready(function($){
var audios = $('.playsong');
var audio = audios.get(0);
audio.load();
$('.play').on('click', function() {
callMeta(audio);
});
$('.song').on('click', function() {
audio = $('.playsong', this).get(0);
callMeta(audio);
});
$('.pause').on('click', function() {
audio.pause();
});
$('.next').on('click', function() {
var i = audios.index(audio);
audio = $(audios).get(i+1);
callMeta(audio);
});
function callMeta(elem){
audios.each(function(i,el) {
if (!el.paused) {
el.pause();
el.currentTime = 0;
}
});
elem.load();
elem.play();
$(elem).on('ended', function() {
$('.next').trigger('click');
});
$('.songtitle').html($(elem).attr('data-songtitle'));
$('.songartist').html( $(elem).attr('data-songartist') );
}
});
Just for clarity - you say the songs have class "song", yet your code says "playsong". A typo, perhaps?
The first song always plays because you always play nowPlaying[i], and i=0 - which only changes when $('.next').on('click', function(){}) is called! You need a way to either change i when a song is clicked, or make the HTML more "modular" (I use this loosely) around each song.
Example HTML:
<audio id="coolSong1">
<!-- Sources -->
</audio>
<!-- I'm not sure what you're using as play, pause, next buttons, so I'll use buttons -->
<input type="button" class="play" name="coolSong1" value="play" />
<input type="button" class="pause" name="coolSong1" value="pause" />
<input type="button" class="next" name="coolSong1" value="next" />
Corresponding script:
$(".play").click(function(event) {
document.getElementById(event.target.name).play();
});
$(".pause").click(function(event) {
document.getElementById(event.target.name).pause();
});

Jquery onblur not working second time

I have build a jQuery PHP based instant search, I have used some fading effect along with onblur event, everything is working fine except when clicking anywhere in body for first time results disappear, but again if hover over to input field to bring result and then clicking in body results do not disappers,
i.e onblur does not work second time.
Please see my code for better understanding and suggest any possible way to do this.
JQuery:
$(document).ready(function () {
$('#search-input').keyup(function(){
var keyword=$(this).val();
$.get('../search/instant-search.php', {keyword: keyword}, function(data){
$('#search-result').html(data);
});
});
$('#search-input').keyup(function(){ $('#search-result').fadeIn(400);});
$('#search-input').blur(function(){$('#search-result').fadeOut(400);});
$('#search-input').click(function(){$('#search-result').fadeIn(400);});
$('#search-input').mouseenter(function(){ $('#search-result').fadeIn(400);});
$('#search-input').mouseleave(function(){ $('#search-result').fadeOut(400)});
$('#search-result').mouseenter(function(){ $('#search-result').stop();});
$('#search-result').mouseleave(function(){ $('#search-result').stop();});
});
HTML:
<input name="keyword" type="text" size="50" id="search-input" value = '';" />
<div id="search-result"></div><!--end of search-result-->
Why have you bind so many events to #search-result??
Check below code if it helps you.
<script language="javascript" >
$(document).ready(function () {
$('#search-input').keyup(function(){
var keyword=$(this).val();
$('#search-result').fadeIn(400);
//$('#search-result').html('ajax result data');
$.get('../search/instant-search.php', {keyword: keyword}, function(data){
$('#search-result').html(data);
});
});
$('#search-input').bind('blur', function() {
$('#search-result').fadeOut(400);
});
$('#search-input').bind('focus', function() {
$('#search-result').fadeIn(400);
});
});
</script>
You can try this:
$('#search-input').on('blur', function() {
$('#search-result').fadeOut(400);
});
$('#search-input').on('mouseleave', function() {
// on mouse leave check that input
// is focused or not
// if not focused the fadeOut
if( !$(this).is(':focus')) {
$('#search-result').fadeOut(400);
}
});
$('#search-input').on('focus mouseenter', function() {
$('#search-result').fadeIn(400);
});
DEMO
According to comment
$('#search-input').on('focus mouseenter', function() {
$('#search-result').fadeIn(400);
});
$(document).on('click', function(e) {
if(e.target.id != 'search-input' && e.target.id != 'search-result') {
$('#search-result').fadeOut(400);
}
})
DEMO

Categories