How to get Information about an element without a callback - javascript

I have different container that get reloaded on different events. I have plenty of them, so I gave each container the class load.
This is how all of them look like:
<div class="load" data-href="facebook">
</div>
I also have a function, that is triggered by various actions:
function get_timing(time)
{
$(".load").load("myfolder/mod_"+$(this).attr("data-href")+".php?action="+time, function() {
alert('Here I could use this:' + $(this).attr("data-href"));
}
}
I know that I cannot use this in the example above, I could only use it in the callback. My question is: How can I use attributes of the object to define the path of the load function.
This is how it could work:
function get_timing(time)
{
$(".load").fadeIn(10, function()
{
$(this).load("myfolder/mod_"+$(this).attr("data-href")+".php?action="+time, function() {
alert('loaded');
}
}
}
Is there a way to do this without the asynchronus function (in this case .fadIn) around)
Hope I could explain my problem - thank you in advance!

If you want to go along with classes you can reference them via an index:
var element = $(".load").get(0);
console.log($(element).attr("data-href"));
Note that you have to re-jQueryfy element via $(element) in order to access attr()
If you want to read out all elements with a given class I recommend $.each()
//$.each($(".load"), function(index, value){
$(".load").each(function(index, value){
console.log( $(value).attr("data-href"));
});

Try to give your container an id:
<div class="load" data-href="facebook" id="facebookcontainer">
</div>
Then instead of using this, you can use $("#facebookcontainer") in your javascript.

Related

Storing .css() method in a variable

I've Googled my face off with no luck including searching this site. I just want a simple clear answer.
Here is my HTML:
<div id="main-navigation">
<ul>
<li>
home
</li>
</ul>
</div>
Here is the css method I'm using which I've tested and works:
// Layout 1
$('#default').click(function() {
if('true' == 'true') {
// General Values
$(hmnavUL).css({ backgroundColor: bgDefault });
});
Here is the variable I've created:
var bgSet = $(hmnavUL).css({ backgroundColor: bgDefault });
Here is what I'm trying to achieve:
// Layout 1
$('#default').click(function() {
if('true' == 'true') {
// General Values
bgSet
});
The result:
The Browser completely ignores my "bgSet" variable, but it acknowledges the style when I don't use a variable. It's not giving me any errors either with my preferred version. Anything you can tell me about my syntax would be appreciated. I'm assuming it's my syntax.
I've linked a photo example to demonstrate the my desired end product (note: I can't attach images yet).
(Default Layout, Second Layout, Remove All Styles)
Desired result: Result
The variable doesn't contain what you expect it to do. The code isn't kept in the variable, it's executed right away and the return value from the css method (which is the jQuery object) is stored in the variable.
You can't put a "macro" in a variable and have it executed by referencing the variable. The closest thing to what you are trying to do would be to put the code in a function, so that it can be executed later:
var bgSet = function() {
$(hmnavUL).css({ backgroundColor: bgDefault });
});
// Layout 1
$('#default').click(function() {
if('true' == 'true') {
// General Values
bgSet();
}
});
It looks like you want to toggle and element's css properties based on click eventHandler. You've got the right idea, but you're javascript is slightly off. Here's an example that should perform the function you want:
// Function to change the css of an element
function makeRed(elem){
elem.css({ "background-color" : "red" });
};
// Attach an event handler..
$("#clickMe").click(function(){
// Store the object as a variable
var obj = $("#foo"); // <-- The element you want to change the bg of
// Run your function.
makeRed(obj);
});
#foo{
width: 50px;
height: 50px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="foo"></div><br />
<button id="clickMe">Click Me!</button>
This is really about learning how javascript selectors, functions and variables work.. Although your question is phrased in a sort-of obtuse way for StackOverflow, I appreciate that you posted your code and that you're trying to learn. :)

jquery show another link then hide itself

I have this following jquery on my view:
$(document).ready(function() {
$(function() {
$('#link1').click(function() {
$('#link2').show();
$('#link1').hide();
$('#frame').attr('src', 'http://google.com/');
});
});
});
$(document).ready(function() {
$(function() {
$('#link2').click(function() {
$('#link1').show();
$('#link2').hide();
$('#frame').attr('src', 'http://yahoo.com/');
});
});
});
On pageload, the link2 is set to hide. What the jQuery does is: when the link with id link1 is clicked, it will show the link with idlink2 and hide itself. And vice versa.
My problem is it seems that my jQuery code can still be simplified. Is there other ways I can do what I wanted with simpler version? Thanks for the help!
Working example : http://jsfiddle.net/cuJBm/
$(document).ready(function() {
$(function() {
var linkSet = $('#link1').add('#link2')
linkSet.click(function() {
linkSet.toggle();
});
});
});
The add method allows you to add a different selector to the set of matchers, thus binding both clicks simultaneously. By saving the constructed set to a variable (linkSet), it stops you from having to traverse the DOM twice.
The only two assumption made here, are
1) That in the initial state only one is visible.
2) That the id structure is meaningful, useful, and classes will not suffice.
http://jsfiddle.net/cuJBm/1/
To answer your second question about setting an attribute on #frame. There are numerous ways of doing this. Perhaps the simplest is to add the following to your .click handler (after the toggle).
if ($(this).attr('id')=='link1'){
$('#frame').attr('src', 'www.google.com');
} else if ($(this).attr('id')=='link2'){
$('#frame').attr('src', 'www.yahoo.com');
}
Personally, I would probably add a custom attribute to your link elements, something like:
<a id='link1' iframe-source='www.google.com'>
<a id='link2' iframe-source='www.yahoo.com'>
And then: (again, just after the toggle):
source = $(this).attr('iframe-source');
$('#frame').attr(src, source);
The reason for saving source if is that if you attempt to get $(this) within the .attr on $('frame'), it will (as always) return the currently matched element, ie $('#frame').
Alternately (and very similiarly to the above approach), you could use the innerHTML of the link. For example:
<a id='link1'>link1<span style="display:none">www.google.com</span></a>
<a id='link2'>link2<span style="display:none">www.yahoo.com</span></a>
And then: (again, just after the toggle):
source = $(this).find('span').text();
$('#frame').attr(src, source);
Personally, I dislike this last method as it pollutes the DOM structure, leading to slightly more expensive rendering times, and (in my opinion) less readable code. Practically, all three methods work just fine.
<p class="link" style="display:none;" data-link="http://google.com/">sfdf</p>
<p class="link" data-link="http://yahoo.com/">ee</p>
$('.link').click(function() {
$('.link').toggle();
$('#frame').text($(this).data("link"));
});
jsfiddle :http://jsfiddle.net/xqDus/1/
Use jQuery toggle()
just add this
Google
Yahoo
target is id of the frame
$(function() {
$('#link1, #link2').click(function() {
$('#link1, #link2').toggle();
});
});

Writing javascript with jquery and using a variable

As a javascript newbie, I am struggling to use a script with a variable that runs a bit of JQuery (and also struggling to use the right language here, I'm sure!)
The action I want to happen is to change the CSS class of a specific div, e.g. #det90, for which I have the following code (I have used the same on a $(window).load(function() and it works on a different set of divs):
$("#MYDIVIDHERE").switchClass("sdeth","sdet",50);
So I wrote the following:
<script type="text/javascript">
$(function revealCode(divID) {
$("#divID").switchClass("sdeth","sdet",50);
})
</script>
and called it from an anchor with:
onClick="revealCode('det90');"
I think the problem is that I don't know how to write the script and pass the variable in the brackets (divID) to the next line (where I've got "#divID"). Any help or pointers to tutorials gratefully received!
Solution
Thanks to all, but particularly to Caleb. I've scrapped the general function and the onClick, added an ID to the anchor and inserted the following for that anchor (and then repeated that for each anchor/div combination I want to use it on ... and it works :D
$("#linkID").click(function() {
$("#divID").switchClass("sdeth","sdet",50);
});
Change your code to: onClick="revealCode('#det90');"
$(function revealCode(selector) {
$(selector).switchClass("sdeth","sdet",50);
})
jQuery is powered by "selectors" -- similar to CSS syntax.
Don't quote your variable name. Just quote the "#" prefix.
<script type="text/javascript">
$(function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
})
</script>
Change to:
<script type="text/javascript">
function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
}
</script>
You don't need $() around the function
$("#divID") will look for an element with the ID divID, and not what was specified in your function parameter
This won't work. revealCode is local to that scope and not known outside. Also, you're not using the argument you've passed into your handler.
If you're using jQuery, use it to bind to the handler as well like this:
jQuery(document).ready(function() {
function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
}
jQuery("#divID").click(function() {
revealCode('det90');
});
});
Move your onclick event handler attachment into javascript code. You should try not to mix your functional code with your html.
Anonymous version:
$('#myDiv').click(function () {
$(this).switchClass("sdeth","sdet",50);
});
Normal version:
var myFunction = function (element) {
$(element).switchClass("sdeth","sdet",50);
};
$('#myDiv').click(myFunction, {element: this});

How do get a parent node without having a starting reference point?

I want to provide a method for my web app that allows a user to call my function anywhere within his code (inside script tags) that will display a fade-in/fade-out message. What I don't know how to do is determine where I am at in the DOM without having a starting reference point.
Function:
function displayMessage(message) {
// Display a notification if the submission is successful.
$('<div class="save-alert">' + message + '</div>')
.insertAfter($('')) // Do not know how to know where to put the message.
.fadeIn('slow')
.animate({ opacity: 1.0 }, 2000)
.fadeOut('slow', function () {
$(this).remove();
});
}
The HTML:
<!-- Some HTML -->
<div>
<script type="text/javascript">
displayMessage("My message.");
</script>
</div>
<!-- Some more HTML. -->
There isn't any reliable way to get this information. You should do what most other libraries do -- have the user pass in the ID or reference of an element to your displayMessage function so that you can use it.
Generally there are two ways, one, as Casablanca noted you provide a div in the DOM to append the message. Second, and this is the one I think you want, is to create a div node on the DOM itself. That way you have total control. After all it is going to fade out when you're done. Might as well kill it from the dom as well. This is what fancylightbox (and I am sure many others) does with the DOM. You'd want to place it right at the beginning of the body, so there are no other containing elements, and style it as you wish - likely so it floats somewhere near the middle of the page like a lightbox/dialog box.
Unless you want to take in a css selector or an id as argument there is also an alternative to create a jQuery widget. This way you can use it like:
$("#msgArea").messageWidget("displayMessage");
or even reuse it many times
$("#msgArea").messageWidget("displayMessage", "message to display");
Sample boilerplate widget:
(function( $ ) {
$.widget("ui.messageWidget", {
// default options
options: { message: undefined},
// constructor
_create: function() {
if (this.options.message !== undefined) {
this.displayMessage(this.options.message);
}
},
// Displays the message
displayMessage: function() {
this.element.append("your div's and messages");
},
// Allows constructor/setter arguments
_setOption: function( key ) {
$.Widget.prototype._setOption.apply( this, arguments );
}
});
}(jQuery));
You probably want to use fixed positioning to put your box at a place relative to the browser's viewport, regardless of where a user has scrolled to in the document.

AJAX - load all div elements

I have a webpage with a number of div elements such as this one:
<div id='ahFyb2JpdGFpbGxlc2FuZGJveHIKCxIA'>
</div>
I would like each div element to call a javascript function when it has loaded, to fill in the div. Ideally I would have liked to do
<div id='ahFyb2JpdGFpbGxlc2FuZGJveHIKCxIA'
onload=getcontent('ahFyb2JpdGFpbGxlc2FuZGJveHIKCxIA');>
</div>
but of course, onloads are not allowed for div elements. Is there a way to do this? I have read in a number of places that jQuery can help for this, but I can't figure out how to code it up. Any help would be very much appreciated!
To do it without jquery, you just need to set the onload for the window, and tell it what to do with each div. But jquery makes this much simpler.
So without:
window.document.onload = function() {
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++)
divs[i].text("blah blah blah");
}
};
It might be innerHTML. I'd have to double check. But that's the gist. With jquery:
$(function(){
$("div").text("blah blah blah");
};
This of course assumes each div gets the same text. If you want it to be based on ID or class, you most certainly want jquery.
PS - Most web pages try to avoid placing javascript event handlers in the actual HTML. If yous set up the event handlers on load, there's no need and the code is cleaner. Jquery definitely helps on this.
If you're basing the content on the ID of the div, a slight modification to Anthony's code should work
document.onload = function() {
var divs = document.getElementsByTagName("div");
for(var i = 0; i<divs.length;i++){
divs[i].innerHTML = getContent(divs[i].id);
}
I would assign a class to the div's that you want to 'autoload' their own content. This makes the markup clearer and the JavaScript more concise.
$(function() {
$('.autoload').each(function() {
// Use AJAX
$.get("service.php", {id: this.id} function(response) {
// Handle server response here
});
// Or a local data island
this.innerHTML = getDataById(this.id);
});
});
With jQuery:
You should consider using $.load() to retrieve html content. It's slightly easier to use than $.get(). Altho it'll use POST semantics if you supply paramters...
In any event, do you really want to make separate calls back to server for each div? .. Perhaps you should consider a single call that sends the accumulated set of div id's awaiting content to a your web-service function, that then subsequently returns a json structure that you can walk thru at success filling divs all in one shot ..
Something like (not-tested!):
$(function() {
var ids = [];
$('div.autoload').each() { function() { ids.push($(this).attr('id')); });
$.get('service.php', {ids: ids}, function (response) {
$.each(response.perdiv, function (i, c) {
$('div#' + c.id).html(c.html);
});
});
});

Categories

Resources