Javascript functions overlapping - javascript

I have two functions that happen when a link is clicked, a box drops down.
<div class='buttons'><a href = '#' onclick = "return false" onmousedown = "javascript:toggleInteractlogin('login')"class='regular' name='save'> Log In </div></a>
<div class='buttons'><a href = '#' onclick = "return false" onmousedown = "javascript:toggleInteractlogin('register')" class='regular' name='save'> Register</div></a><br><br>
<div class = "Interactlogin" id = "login"> Login</div>
<div class = "Interactlogin" id = "register"> Logina</div>
When login is clicked, the log in box slides down, but then when the register box is clicked, the login box slides further to accommodate for the register box whereas i would like only one box to be shown at a time.
Any help is appreciated.
function toggleInteractlogin(x)
{
if($('#' + x).is(":hidden"))
{
$('#'+x).slideDown(200);
}
else
{
$('#'+x).hide();
}
$('Interactlogin').hide();
}

I have updated the solution in LIVE DEMO - JSFiddler
HTML
<div class='buttons'>
<a id="btnlogin" href= '#' class='login' name='save'>Log In </a>
</div>
<div class='buttons'>
<a id="btnregister" href='#' class='regular' name='save'>Register</a>
</div><br><br>
<div class="Interactlogin" id="login" style="display:none">Login</div>
<div class="Interactlogin" id="register" style="display:none">Logina</div>​
JS
$('#btnlogin').click(function(){
$('#login').show();
$('#register').hide();
});
$('#btnregister').click(function(){
$('#login').hide();
$('#register').show();
});
​

make sure you slide up the register box first when login button is clicked, similarly make sure you slide up the login button first when when register button is clicked
so for loginn button click
1 slide up the register box
2 then slide down the login box
similarly for register
1 slide up the login box
2 then slide down the register box.
try specifying different ids to login & register button
function toggleInteractlogin(x)
{
if(x=='register')
{
$('#login').hide();
$('#register').show();
}
else
{
$('#register').hide();
$('#login').show();
}
}
for show/hide you can specify different effect as well like fadein/fadeout

You can simplify this a bit using this revised markup:
<div class='buttons'><a href='#' class='login'>Log In</a></div>
<div class='buttons'><a href='#' class='register'>Register</a></div>
<br><br>
<div class = "Interactlogin" id = "login">Login</div>
<div class = "Interactlogin" id = "register">Logina</div>
$('.login,.register').mousedown(function() {
$('.Interactlogin').hide();//hide them all initially
var myType = $(this).attr('class');//assumption this is the only class
$('#' + myType).slideDown(200);
});
I assume this CSS to hide initially:(yours may differ)
.Interactlogin{display:none;}

Related

Replace div element not working in JQuery?

In my use case I have question title and question text labels. When I press edit button I want replace the labels with Text boxes with question title and question text. Also submit and cancel buttons for edit. In this edit if I press cancel I should replace with original div content. The following code is working until cancel. When I press cancel it is not properly replacing the original content. Also the edit button got disabled. I didn't disable edit button anywhere manually.
JQuery code:
//global variable for question edits
var originalQuestion = "";
//Enables and disables the question elements
//for all questions
$('.questiondiv').on('click', '.edit_question_button', function() {
console.log("In submit edit question text area");
var pageURL = $('#page_url').text();
var loggedUser = $('#logged_user').text();
if (!loggedUser) {
console.log("In answerbutton redirect");
window.location.href = "/login/?redirect="+pageURL;
} else {
console.log("question edit");
title_val = $(this).closest('.question-inner').find('.quest_title_val').text();
question_val = $(this).closest('.question-inner').find('.quest_text_val').text();
console.log("question edit logged in 2");
console.log("Question title value ", title_val);
console.log("Question value ", question_val);
newdiv = "<div class='form-input updated_question'><input name='question_title_val' class='question_title_val' type='text' size='81' value='"+title_val+"' /></div> <br /> <div class='form-input'><textarea name='question_text_val' class='question_text_val' rows='8' cols='80'>"+question_val+"</textarea><br /><div class='form-input'><a type='Submit' id='updatequestion' name='updatequestion' class='btn btn-primary updatequestion'>Update Question</a><a type='Cancel' id='cancelupdatequestion' name='cancelupdatequestion' class='btn btn-primary cancelupdatequestion'>Cancel</a></div></div>";
originalQuestion = $(this).closest('.questiondiv').html()
$(this).closest('.question-inner').replaceWith(newdiv);
}
});
//updates question
//question ID may have to added as
//hidden element in the html
$('.questiondiv').on('click', '.updatequestion', function() {
console.log("In update question button");
var question_id = $(this).closest('li').find('.question_id_val').val();
var quest_title = $(this).closest('.updated_question').find('.quest_title_val').text();
var quest_val = $(this).closest('.updated_question').find('.quest_text_val').text();
console.log(quest_title);
console.log(quest_val);
$.getJSON("/question?question_id="+question_id+"&question_title"+quest_title+"&question_val="+quest_val, function(data) {
console.log("update question Response "+data);
$(this).closest('.updated_question').replaceWith(originalQuestion);
});
//$(this).closest('.answersectiondiv').remove();
});
//cancel updatequestion elements
$('.questiondiv').on('click', '.cancelupdatequestion', function() {
console.log("In cancel update question area");
//console.log("Original question div tag ", originalQuestion)
$(this).closest('.question-inner').replaceWith(originalQuestion); //Again use this to remove only parent container div
//$(this).closest('.questiondiv').find('.edit_question_button').prop( 'disabled' , true );
});
HTML code:
<div class="qanda questiondiv" id="questionarea" name="questionarea">
<div class="question-inner">
<div>
<div id="topic" class="upvote pull-left">
<a class="upvote"></a>
<span class="count">3</span>
<a class="downvote"></a>
</div>
<div >
<div class="qanda-info">
<h6><p class="quest_title_val">{{.QuestionTitle}}</p></h6>
</div>
<p class="quest_text_val">{{.QuestionText}}</p>
</div>
</div >
<div class="qanda-info">
<div class="user-info">
<a href="/userprofile/{{.UserId}}" ><img src="http://tinygraphs.com/spaceinvaders/Dany?theme=frogideas&numcolors=4&size=220&fmt=svg"/>
</a>
</div>
<h6>{{.UserId}}</h6>
<span class="date alt-font sub">{{.DateCreated}}</span>
[<a class="edit_question edit_question_button" >edit</a>|<a class="delete_question_button" id="deleted" ">delete</a>]<br>
<a id="answertext" name ="answertext" type="submit" class="link-text answerbutton">Answer</a>
</div>
</div>
</div>
Could someone help me with this? Thanks

Dynamically Populate JQUERY Mobile Multi-Page Page

JQUERY Mobile Beginner Question: I have two pages in my simple multi-page JQUERY Mobile 'App'. When the user navigates to PAGE2, I want to do an AJAX call to get a JSON object containing a list of people + DB ID pairs. I want to present the list of people as buttons on PAGE2.
Code Snippet:
<div id="PAGE2" data-role="page">
<div class="ui-content">
// I want buttons to appear sequentially here
</div>
</div>
PAGE2 is my "placeholder" to populate with:
<input type="button" id="id1" name="id1" value="Bob Smith"/>
<input type="button" id="id2" name="id2" value="Jane Doe"/>
<input type="button" id="id3" name="id3" value="Kayla Kaye"/>
I'd also need to add a 'click' event handler in the script to react to the buttons. The reaction will be the same for all buttons (dynamically populate a PAGE3 with people detail, but I think I can figure that out if I see how PAGE2 population is correctly handled). What is the proper way to go about dynamically "creating" PAGE2 using the skeleton in place?
if jquery is allowed:
var elements = { id1:'Bob Smith', id2:'Jane Doe', id3:'Kayla Kaye'};
$.each( elements, function( key, value ) {
$("#PAGE2 .ui-content").append('<input type="button" id="' + key + '" name=" + key " value " + value +'"/>');
}
You can try this
$('#PAGE2').on('pagebeforeshow', function(){
var people = [
{ name:'Bob Smith', age:'56', place:'London'},
{ name:'John', age:'65', place:'USA'},
];
var btns;
$.each(people,function(indx,ppl){
btns = btns + '<input type="button" name="id1" value="' + ppl.name +'"/>';
});
$('#content_div').html(btns);
});
set id to div content to content_div
Here is a DEMO
With your 3 pages setup like this (I have added container divs for the buttons and details):
<div data-role="page" id="PAGE1">
<div data-role="header">
<h1>PAGE 1</h1>
</div>
<div role="main" class="ui-content">
Go to page 2
</div>
</div>
<div data-role="page" id="PAGE2">
<div data-role="header">
<h1>PAGE 2</h1>
</div>
<div role="main" class="ui-content">
<div id="thePeople"></div>
</div>
</div>
<div data-role="page" id="PAGE3">
<div data-role="header">
<a data-rel="back" class="ui-btn ui-btn-icon-left ui-icon-back">Back </a>
<h1>PAGE 3</h1>
</div>
<div role="main" class="ui-content">
<div id="theDetails"></div>
</div>
</div>
You can use the pagecontainer widget's beforeshow event to make your ajax call:
http://api.jquerymobile.com/pagecontainer/#event-beforeshow
In my example, I am checking where you are coming from and where you are going to. So coming from PAGE1 to PAGE2, I make the AJAX call and create the buttons. But if returning from PAGE3 to PAGE2, I just leave the already created buttons alone. Ater adding the buttons to the page, make sure and call .enhanceWithin() on the container so that jQM enhances the buttons.
$(document).on( "pagecontainerbeforeshow", function( event, ui ) {
var prevID = ui.prevPage.prop("id");
var newID = ui.toPage.prop("id");
if (prevID == "PAGE1" && newID == "PAGE2") {
//we have come from page 1 to page 2, so make AJAX call and populate page 2
var data = [
{ "id": "id1", "name":'Bob Smith'},
{ "id": "id2", "name":'Jane Doe'},
{ "id": "id3", "name":'Kayla Kaye'},
];
var buttons = '';
$.each(data, function(indx){
buttons += '<input type="button" name="' + this.id + '" value="' + this.name +'"/>';
});
$("#thePeople").empty().append(buttons).enhanceWithin();
}
});
Finally, when PAGE2 is created, I use event delegation to create a click event for any buttons that might be added (with event delegation, the buttons don't have to exist at the time the event is bound). In the event, get the id/name for the button that is clicked, get the details (Another AJAX call?), populate PAGE3, and then navigate to PAGE3 using the pagecontainer widget change method:
http://api.jquerymobile.com/pagecontainer/#method-change
$(document).on("pagecreate","#PAGE2", function(){
$(document).on('click', '#thePeople input[type="button"]', function(e){
var personid = $(this).prop("id");
var name = $(this).val();
$("#theDetails").text('Details for ' + name);
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#PAGE3", { transition: "slide" });
});
});
DEMO

Execute javascript again with load function

I want to create a "next" button which display different profiles. For that, I want to reload the div. I have successfull create the function, but when It's reload 1 time, javascript is not load after, so my button click function doesn't work.
My code :
<div class="col-md-6">
<div class="my" id="profile_rd">
<div class="ibox-content text-center" id="ok">
<h1>Profile example</h1>
<a class="btn btn-xs btn-prim-red" id="please_next"><i class="fa fa-chevron-right"></i> Next</a> <!-- Here, we can click and execute the function one time , after, click doesn't work -->
</div>
</div>
</div>
<script>
$('#please_next').click(function(){
$('#profile_rd').load(document.URL + ' #ok');
return false;
});
</script>
Try changing
$('#please_next').click(function(){
$('#profile_rd').load(document.URL + ' #ok');
return false;
});
to
$(document).on( 'click', '#please_next', function(){
$('#profile_rd').load(document.URL + ' #ok');
return false;
});
You're reloading the document so after the first click on the button, the DOM can't find the element that you're trying to attach the event to. You need to use event delegation.

Open accordion using onfocus on input field

I am trying to open accordion on onfocus on input field.I have tried but it is not happening .i want to open accordion depending onwhich input box is focus
<input type="text" id="rnv" class="form-control" placeholder="Ex: Roasted Aparagus and Musherooms" onfocus="accordion('rntip',this)">
<textarea class="form-control" id="in" rows="6" placeholder="Ex: bunch fresh asparagus, trimmed; 2 sprigs fresh rosemary, minced" onfocus="accordion('intip',this)"></textarea>
<script type="text/javascript">
function accordion(id,obj){
$(document).ready(function(){
var accordion = id;
var accordionContent = accordion.next('.accordion-content');
var accordionToggleIcon = $(this).children('.toggle-icon');
// toggle accordion link open class
accordion.toggleClass("open");
// toggle accordion content
accordionContent.slideToggle(250);
// change plus/minus icon
if (accordion.hasClass("open")) {
accordionToggleIcon.html("<i class='fa fa-minus-circle'></i>");
} else {
accordionToggleIcon.html("<i class='fa fa-plus-circle'></i>");
}
});
}
</script>
<div class="accordion-container"> <span class="toggle-icon"><i class="fa fa-plus-circle"></i></span>Recipe Name
<div class="accordion-content">
<ul>
<li>Keep it short.</li>
<li>Include the name of the dish or its main ingredients.</li>
<li>Add a personal touch/get creative.</li>
</ul>
</div>
</div>
Make sure accordion is referencing the accordion element and not just the string you pass.
Change var accordion = id; to var accordion = $("#"+id);

how to use javascript event handler

I have a 2 col layout, on the left i have a button that says show code and on the right i have some html.
The above is repeat numerous time so i have a list of buttons that i want related to the "widget" next to it.
If i click on each button, i would like to show the innerHTML of the element to the right in an alert box.
My right column html widgets are a class called "mywidgets", and my buttons to the left have a class called "showcode"
how would I go about showing the code of the related box to the right on click of button to the left in javascript or jquery?
if I do something like:
var showthem = document.getElementsByClassName('mywidgets');
for (var i=0; i < widgetBits.length; i++) {
};
but I get confused on how to count each button and each class in the seperate area, then show the code on click.
I was also thinking about something similar to below but again I get confused on how to utilize "this"/each item clicked.
$(document).ready(function(){
$("button").click(function(){
$("mywidgets").clone().appendTo("myareofchoce");
});
});
HTML:
left area :
<div class="container marginBTM10">
<div class="row">
<div class="col-lg-offset-2 col-md-offset-2 col-lg-10 col-md-10 bgColor_FFF padding10">
<h2>Widget 1</h2>
<div class="highlight">
<button class="btn btn-primary btn-sm " onclick="widgets()">get code</button>
right hand area :
<div class="col-lg-4 col-md-4">
<!-- widget 1 starts-->
<div class="sortable bgColor_FFF mywidgets">
<div class="padding10">
stuff
</div>
</div>
<!-- widget 1 ends-->
</div>
</div>
http://jsfiddle.net/wne6rnda/1/
to connect buttons and widgets must be used in a single tag.
in this case: widget has id and corresponding button has data-id with same value
HTML:
buttons:
<button class="btn btn-primary btn-sm get_class" data-id="#mywidgets1">
...
<button class="btn btn-primary btn-sm get_class" data-id="#mywidgets2">
...
widgets:
div class="sortable bgColor_FFF mywidgets" id="mywidgets1">
...
div class="sortable bgColor_FFF mywidgets" id="mywidgets2">
...
JQ
$('.get_class').click(function () {
//get id of selected widget
var id = $(this).data('id');
//get selected widget
var $widget = $(id);
//clon and add selected widget
$widget.clone().appendTo(".myareofchoce");
})
UPDATE: 2
http://jsfiddle.net/wne6rnda/9/
$('.get_class').click(function () {
var id = $(this).data('id');
var $widget = $(id);
var html=$widget.html();
//solution 1 - output to the textarea
var txt=$(".myareofchoce2").val();
$(".myareofchoce2").val(txt+"\r\n"+html);
//solution 2 - use <xmp> tag
html='<xmp >'+html+'</xmp >';
$(".myareofchoce").append(html);
})

Categories

Resources