Removing Yet not Deleting an Element/Variable from an HTML Document - javascript

I am testing out with a different way of menus. My code is the following:
JavaScript
var hubOpen = 0;
var test = "test";
$(document).ready(function(){
$('#hub').click(function(){
if(hubOpen == 0){
$('#hub').append(test);
hubOpen = 1;
} else {
//code for taking "test" out here
hubOpen = 0;
};
});
});
HTML
<body>
<p id="hub">Hub</p>
</body>
If you'd like, here's a jsFiddle here. The code is to make sure that when the id "hub" is clicked, "test" appears. When hub is clicked again, "test" disappears. The code, when run, opens test, doesn't let you click it again, but it doesn't delete "test" (as there is no code for it).
My question: How would I delete the variable "test" from the document but not to delete the variable forever, as I would need to use it later? Would the jQuery method
.replace();
work?
Thanks in advance!

To remove all the contents of an element, jQuery offers .empty():
$('#hub').empty();
The variable is completely separate from the element, so no problems there. If you wanted to restore the original text, just use .text():
$('#hub').text('Hub');
Updated fiddle

You can do something like this:
$(document).ready(function(){
$('#hub').click(function(){
$(this).text() == 'Hub' ? $(this).html('text') : $(this).html('Hub');
});
});
On click if the text is 'Hub' change it to 'text' else change it again to 'Hub'.

Related

Activate hover action on a certain word

Okay, so this is something that has already been done so I know it's possible. What I'd like is that, when the user hovers the mouse on some word defined by the wordHoverAssign() function, something would get activated.
So, in a more concise manner: When the page is loaded the text I love potatoes! shows up on screen, created with HTML. Then the function wordHoverAssign("potatoes") is executed. What should happen then, when I hover the word potatoes, is that an alert message would pop up with, for example, this message You hovered the word!.
Is this possible? How would I go about doing it? I'd really like it if I didn't have to use any more frameworks/plugins. I'm using jQuery by the way.
Thank you.
My code so far (if you don't feel like setting it up):
wordHoverAssign("potatoes");
function wordHoverAssign(theWord) {
//code here
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>I love potatoes!</p>
The following allows you to assign different function to any word inside the #content div. The associated function is called only when the specific word is hovered.
<div id="content">
I love potatoes!<br/>
She loves something else<br/>
The potatoes coming again.
</div>
<script>
window.wordsAssigned = {};
function wordHoverAssign(word,func){
wordsAssigned[word] = func;
}
wordHoverAssign('potatoes',function(){
alert('Patatoes hovered!');
});
wordHoverAssign('something else',function(){
alert('something else!');
});
$(function(){
var content = $('#content');
var html = content.html();
for(var word in wordsAssigned){
html = html.replace(new RegExp(word,"gm"),'<span onmouseover="wordsAssigned[\''+word+'\']()">'+word+'</span>');
}
content.html(html);
})
</script>
As per your need :contains('text') suits you better. see example:
wordHoverAssign("potatoes");
function wordHoverAssign(theWord) {
$( ":contains("+theWord+")" ).hover(function(){
alert("Hover happend");
})
}
Here is Updated DEMO
But above code will alert twice because of hover event also bind with body, so my suggestion is use special tag. See following snippet:
wordHoverAssign("potatoes");
function wordHoverAssign(theWord) {
$( "p:contains("+theWord+")" ).hover(function(){
alert("Hover happend");
})
}
Another DEMO for hover in p tag. It won't work on body hover.

CasperJS click is leads to error even when the element exists

I'm trying to click on a logout button, which I have retrieved from the current page. I successfully got the id of the logout link. But when I click on it, an error occurs
Cannot dispatch mousedown event on nonexistent selector
function getLogoutId()
{
var logoutid = "";
$(document).find("a").each(function(key,value){
var id = $(this).attr("id");
if(id.toLowerCase().indexOf("logout") > -1)
{
__utils__.echo("insidelogout" + id);
logoutid = id;
}
});
return logoutid;
}
var logoutid = this.evaluate(getLogoutId);
fs.write("logout.txt", this.getHTML(), 'w');
this.thenClick("#"+logoutid, function(){});
I have written the html content to a file, in which I checked for the id and it is there. The id attribute in question looks like this:
et-ef-content-ftf-flowHeader-logoutAction
I see nothing wrong with your code aside from strange usage of jQuery.
You can try other CSS selectors for clicking:
casper.thenClick("[id*='logout']"); // anywhere
or
casper.thenClick("[id$='logoutAction']"); // ending
or
casper.thenClick("[id|='logoutAction']"); // dash-separated
Maybe it is an issue with the code that follows the shown code. You can try to change thenClick to click.
Have you tried using just this.click("#"+logoutid);?
Also have you considered using jQuery to click on the button? Something like this...(first make a variable of your id so you can pass into jQuery).
var id = "#"+logoutid;
this.evaluate(function(id){
jQuery(id).click();
},id);

Javascript getElementById value setting getting reset on function return

I have a simple function to show / hide a div element. I have a javascript function to do that. I debugged this with Opera. The function sets the hidden value properly on the div element. I can see the div element disappear. However, when the function returns the div element reappears. The javascript function is in its own file:main.js:
function showhide(name){
var elem = document.getElementById(name) ;
if( elem.hidden == false ) {
document.getElementById(name).hidden = true ;
} else {
document.getElementById(name).hidden = false ;
}
}
The Html is:
<div class=wrap><p>
<div class=sidebar>
<FORM><input type="submit" value="Toggle" onclick="showhide('specname');"/></FORM></div>
<div class=main>main Div
<div id="specname">collapsible text</div></div></p></div>.
I have set debugging breakpoints in the javascript function showhide to see that the value is being set properly. But on function return, the value is reset.
It is probably something simple I am missing but can't seem to see it? Any ideas? Thanks!
The answers solved my problem. I was missing the fact that the submit repainted the page and I lost my changes. I changed the type=submit to type=button. And I removed the form to just an input element with type button. That worked very nicely. Thanks everyone for your help!!! I really appreciate your answers!
The following wont do anything in some browsers:
document.getElementById(name).hidden = true
change it to
document.getElementById(name).style.display = 'block' // and 'none' for the matching line
does that make it do what you need?
As others have pointed at, it is also submitting the page - either use a different element or change the function to start :
function showHide(e, name) {
e.preventDefault();
//do the toggle here
return false;
}
The problem is you are using a submit control which will submit to the server and refresh the page. You want to stop the submit or change the control type. Both of the following should work. I recommend the 2nd one.
Try this
<FORM><input type="submit" value="Toggle" onclick="showhide('specname'); return false;"/>
or this
<input type="button" value="Toggle" onclick="showhide('specname');"/>
Probably because when you click the button the form submits and it refreshes the page ?
You should not be using a form just to have a button that does something. Instead, try using
<button onClick="showhide('specname');">Toggle</button> (and get rid of the form entirely)
Try this for your showhide().
function showhide(name){
var elem = document.getElementById(name);
(elem.style.visibility == 'hidden'?elem.style.visibility = 'visible':elem.style.visibility = 'hidden');
}
OR similarly:
function showhide(name){
var elem = document.getElementById(name);
(elem.style.display== 'none'?elem.style.display= 'inline':elem.style.display= 'none');
}
Maybe try them both and see which you need.
Cheers.

Fancybox - Setting the parent window's global variable from within a child fancybox

Here is the issue at hand:
The overall development is being done using Ruby on rails; however, the views consist of mostly html and jQuery. Currently, I have it set up so that when a user types into a text field, they can press a small "suggest" button beneath it which opens up a Fancybox where there is a list of useful Search terms, provided by the Google Suggest API. This is all set up and working. Now I want to take this to the next step, where, from inside of the Fancybox, the users can click on one of the suggestions and it will replace the initially typed in phrase in the parent window. Sadly I am not adept at using AJAX yet so I am trying to do this via javascript. This is what I have thus far:
In the parent window:
<script type="text/javascript">
$(document).ready(function() {
var $_returnvalue = false;
$('.suggest_link').fancybox({
onClosed: function(){
alert($_returnvalue);
if ($_returnvalue != false)
{
// I will be setting the textbox value here.
}
}
});
</script>
In the partial view rendered inside of the fancybox:
<script type="text/javascript">
$(document).ready(function() {
var $_fancyvalue = false;
$(".suggestion").click(function(){
alert(parent.$_returnvalue);
parent.$_returnvalue = $(this).text();
$.fancybox.close();
});
});
</script>
Sorry if there is anything strange with this post. This is my first time asking a question here.
Define var $_returnvalue in the global scope in the parent window. Try this it will work fine.
var $_returnvalue = false;
$(document).ready(function() {
$('.suggest_link').fancybox({
onClosed: function(){
alert($_returnvalue);
if ($_returnvalue != false)
{
// I will be setting the textbox value here.
}
}
});

jQuery event delegation with non-trivial HTML markup?

I have two DIVs, first one has a link in it that contains the id of the second DIV in its HREF attribute (complete setup on jsbin).
I want to animate the second DIV when user clicks on the first - anywhere on the first. I also want to use event delegation because I'll have many such "DIV couples" on a page (and I'm using a JS snippet from this SO answer).
If user clicks on the DIV itself, it will work - just check firebug console output. The problem is, if user clicks on one of the SPANs or the link itself, it doesn't work anymore.
How can I generalize the click handler to manage clicks on anything inside my DIV?
Here's the JS:
$('#a').click(function(e) {
var n = $(e.target)[0];
console.log(n);
if ( n && (n.nodeName.toUpperCase() == 'DIV') ) {
var id = $(n).find('a').attr('hash');
console.log(id);
$(id).slideToggle();
}
return false;
});
It took me so long to write up the question that I decided to post it anyway, perhaps someone suggests a better way.
Here's the solution I found (jsbin sandbox):
$('#a').click(function(e) {
var n = $(e.target)[0];
var name = n.nodeName.toLowerCase() + '.' + n.className.toLowerCase();
if (n && (name === "div.clicker" || $(n).parents("div.clicker").length )) {
var id = $(n).find('a').attr('hash');
if(!id) {
id = $(n).parents("div.clicker").find('a').attr('hash');
}
console.log(id);
}
return false;
});
Here is my solution. Not sure if that's exactly what you wanted, but it works for me.
$(document).ready(function() {
$('#a').click(function() {
var a = $("a", this);
$(a[0].hash).slideToggle();
});
});
Edit: Tested in both IE7 and Fx3
Edit: In that case...
$(function() {
$("a.tab").click(function() {
$($(this).attr("hash")).slideToggle();
return false;
});
});
Something like that might work (putting the tab class on anything that has a div "attached" to it). However, I'm not sure unless I actually see an example of it. Although if you want it to work when clicking on the span...you would attach the class to the span, and instead do:
$(function() {
$("span.tab").click(function() {
var a = $("a",this);
$(a.attr("hash")).slideToggle();
});
});
Not sure if you want an open div to close if another one is opened. If this doesn't solve your problem, it would help if you would put up an example on jsbin...

Categories

Resources