Triggering a function on multiple events - javascript

I've written some code to collapse 2 columns if the text on the left is longer than the image on the right:
var collapsed = null;
var banner = function() {
var txt = $('.banner .text').outerHeight();
var image = $('.banner .main-image').outerHeight();
if (txt > image) {
// Collapse columns
$('.banner').addClass('single-line');
// Set the breakpoint the column collapsed at
if (collapsed == null) {
collapsed = $(window).width();
}
}
// Restore the 2 columns when the browser hits the breakpoint
if ($(window).width() >= collapsed) {
$('.banner').removeClass('single-line')
}
}
My problem is getting this function to trigger at the right times. This works:
$(window).resize(banner);
But neither of these work...
$(window).onload(banner); // When the page first loads
$(window).on('orientationchange', banner); // When device is rotated
I could be completely on the wrong tracks here, so please feel free to point me in the right direction.
Thanks in advance!

Acording to the documentation of JQuery,there is no "onload" method for the jquery object, instead you should use "ready":
$(window).ready(banner);
About this line not getting fired, probably because you"re using the wrong synthax. The reference for "on" method :
.on( events [, selector ] [, data ], handler )
so you should try this :
$(window).on('orientationchange','window', banner)
Cheers

To run when the page first load, you can use:
$(document).ready(function() {
banner();
});
Regarding the orientationchange event, make sure you are using the jquery.mobile.js (https://api.jquerymobile.com/orientationchange/)

Related

Javascript, passing my string as an argument turns it to a 0

I'm using scrollmagic.io and am making an anchor navigation menu. I'm following this tutorial. The scroll works! Except it was scrolling back to the beginning and not to the page it should be at.
Here is my code:
// init controller
var controller = new ScrollMagic.Controller();
// animate scroll instead of a jump
controller.scrollTo(function(target) {
console.log('scroooooll');
console.log('target = '+target); // THIS IS PRINTING 0
console.log(typeof(target));
/* Commenting out what it should do for simplicity. */
});
// scroll action when you click the nav links
$(document).on('click', 'a[href^=#]', function(e) {
var id = $(this).attr('href'); // get the href of clicked link
if ($(id).length > 0) { // not empty links
e.preventDefault(); // prevent normal link action
// this is the function call
console.log('click');
console.log('id = '+id); // IT PRINTS CORRECT HERE
console.log(typeof(id));
controller.scrollTo(id); // scroll on click
// update the URL
if (window.history && window.history.pushState) {
history.pushState("", document.title, id);
}
}
});
And here is the output of my console log:
click
id = #{the-href-value}
string
scroooooll
target = 0
number
My Javascript is pretty rusty, but this doesn't seem right to me. Why is it changing my variable from a string to a 0 when I pass it as a parameter?
From the documents:
"This function will be used for future scroll position modifications.
This provides a way for you to change the behaviour of scrolling and
adding new behaviour like animation. The function receives the new
scroll position as a parameter and a reference to the container
element using this. It may also optionally receive an optional
additional parameter (see below)"
So, the first parameter is passed by controller.
You will get your parameter after that.
http://scrollmagic.io/docs/ScrollMagic.Controller.html#scrollTo
Try printing console.log(args);
controller.scrollTo(function(scrollPos, targetHrefISent) {
console.log('scroooooll');
console.log('target = '+targetHrefISent); // THIS IS PRINTING 0
console.log(typeof(targetHrefISent));
/* Commenting out what it should do for simplicity. */
});

javascript to check a link for string & launch modal

Have a page containing links.
When a link is clicked I want Javascript (or other) to check if the link contains (e.g. cheese)
If if does, then a modal should launch displaying the link.
example:
http://mylink/just-normal/ -- when this clicked, should proceed as normal
http://mylink/with-cheese/ -- when this clicked, should launch modal
http://mylink/another-link/ -- when this clicked, should proceed as normal
http://mylink/other-link/ -- when this clicked, should proceed as normal
Modal should display the full link.
Any assistance is appreciated.
Below is what I've got so far.
My specific question is:
Question: When I click any link on the site, a modal opens. It seems to be targeting all links and not just the links containing the specific word(s).
jQuery(function () {
jQuery(document).on('click', jQuery('a') , function(event){
var e = event;
event.preventDefault;
var that = event.target;
if(jQuery(that).is("span")){
that = jQuery(event.target).parent();
}
if(jQuery(that).attr('href')){
var url = jQuery(that).attr('href').toLowerCase();
if(jQuery.browser.webkit || jQuery.browser.mozilla && (url.indexOf('.my.test.here/') >=0)) {
ie_pointer(e, that);
}
else if (jQuery.browser.webkit && || jQuery.browser.mozilla (url.indexOf('something.else/') >=0)){
var overall = jQuery('.overall');
ie_pointer(e, overall, that);
}
}
});
});
function ie_pointer(event, obj, that){
event.preventDefault();
if(that){
var url = jQuery(that).attr('href');
}
else{
var url = jQuery(obj).attr('href');
}
jQuery('<div class="modal-backdrop"></div>').hide().appendTo(document.body).fadeIn();
jQuery(obj).after('<div class="modal-content" style="padding:10px"><h3 style="color:#333">Please copy the blue link below into Internet Explorer</h3><p style="font-size: 1.2rem; color:#333">This form is currently unavailable in Firefox & Chrome.</p><h4 style="color: #0099cc; max-width: 400px; word-wrap:break-word;">'+url+'</h4><i onclick="close_modal()" class="icon-remove"></i></button></div>');
}
function close_modal(){
jQuery(".modal-backdrop").fadeOut(function(){jQuery(this).remove()});
jQuery('.modal-content').fadeOut(function(){jQuery(this).remove()});
}
Your click event handler is set up for event delegation so that it only responds when event.target is an <a>:
jQuery(document).on('click', jQuery('a') , function(event){
Yet, inside of the handler, you have this:
if(jQuery(that).is("span")){
that = jQuery(event.target).parent();
}
Since you have that set to event.target, this if condition will never be true, so I'm not sure what you are trying to accomplish with it.
The remainder of the function runs when the <a> element has an href, but there too, you have if conditions that don't quite make sense:
if(jQuery.browser.webkit ||
jQuery.browser.mozilla && (url.indexOf('.my.test.here/') >=0)) {
ie_pointer(e, that);
} else if (jQuery.browser.webkit && ||
jQuery.browser.mozilla (url.indexOf('something.else/') >=0)){
var overall = jQuery('.overall');
ie_pointer(e, overall, that);
}
Your first condition will be true if the browser is webkit or if it is mozilla and the attribute contains your test string. Why don't you want to test for the string when the browser is webkit?
Your else if condition does the same thing, but you have a syntax error in it because you forget && here:
jQuery.browser.mozilla (url.indexOf('something.else/') >=0))
And, perhaps more importantly, why do you care what browser it is? JQuery deprecated the browser flags in version 1.9 because they are based on the navigator.userAgent, which has always been an unreliable way of browser sniffing.
Here's a slimmed down example of getting links that contain a certain string in their href to do one thing and all others to do something else using the standard CSS attribute selector:
var url = "console";
// Simply use the attribute wildcard selector to make sure
// you are only selecting links you care about in the first place
$("a[href*='" + url + "']").on("click", function(evt){
evt.preventDefault();
alert("You clicked a link that I care about!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I should cause an alert().<br>
I should cause an alert().<br>
I should NOT cause an alert().<br>
I should NOT cause an alert().

JS fails reading upcoming array elements

The goal is to create navigation out of a JSON-file in the #left div-box. There should be links to the previous/next page according to the file hierarchy in the #right div-box.
My implementation is running very weirdly. When you click on a link in the navigation, only the link to the previous page shows up. By clicking on said previous link, the one to the next page is updating as well. Navigating through those 2 previous/next links works. As soon as you switch back to navigating through the navigation on the left the next page link won't update anymore. The previous one still does.
Try it out yourself:
http://jsfiddle.net/cxdL3/6/
From what I found out the problem is reading an element ahead in the array ([subchap+1]) doesen't always work. Which confuses me as it should be loaded before the functions are getting called.
Do you have an explanation for that behavior? The two links are also basically created the same way.
var chap; //position in the array of the currently open chapter
var subchap; //position in the array of the currently open subchapter
function update_right() {
var path = data.chapter[chap].subchapter;
//Previous Page
if(subchap > 0) {
$("#prev").html("<b>Previous: </b><a href='"+path[subchap-1].url+"'>"+path[subchap-1].title+"</a><br/>");
$("#prev > a").click(back);
} else { //subchap == 0
$("#prev").html("");
};
//Next Page
if(subchap+1 < path.length) {
$("#next").html("<b>Next: </b><a href='"+path[subchap+1].url+"'>"+path[subchap+1].title+"</a><br/>");
$("#next > a").click(next);
} else {
$("#next").html("");
}
}
function back() {
subchap--;
update_right();
}
function next() {
subchap++;
update_right();
}
$(document).ready(function() // DOM needs to exist in order to be able to add stuff in there
{
//... Navigation created ...
//------ onClick Navigation
$('#left > ul > li > a').click(
function()
{
chap = $(this).attr("data-chap");
subchap = $(this).attr("data-subchap");
update_right();
}
);
});
The remaining files are pretty standard. In case they matter, they can be found here: http://fabitosh.bplaced.net/SkriptET_iFrame_v3/
When getting chap and subchap values in your click handlers, get them as integers, not strings:
chap = parseInt($(this).attr("data-chap"), 10);
subchap = parseInt($(this).attr("data-subchap"), 10);
so that things like chap + 1 become 1 when chap == 0, instead of "01" when chap == "0"
Updated example: http://jsfiddle.net/cxdL3/10/
If you use $(object).data('chap'), jQuery will handle the type conversion for you.

Expand only one row in javascript code

hey guys having trouble figuring out how to make it so that i can make it only open one table at once, once you open another the other should close any help here?
function showRow(cctab){
if (document.getElementById(cctab)) {
document.getElementById(cctab).style.display = '';
}
}
function hideRow(row1){
if (document.getElementById(cctab)) {
document.getElementById(cctab).style.display = 'none';
}
}
function toggleRow(cctab){
if (document.getElementById(cctab)) {
if (document.getElementById(cctab).style.display == 'none') {
showRow(cctab)
} else {
hideRow(cctab)
}
}
}
Now I want to make it so that only one table "cctab" opens after I suggest the onClick="javascript:toggleRow(cctab);" anyhelp?
Well you could save a reference to the previously shown item and hide it when another is shown:
var currentTab;
function showRow(cctab){
if (document.getElementById(cctab))
document.getElementById(cctab).style.display = '';
if (currentTab && currentTab != cctab)
hideRow(currentTab);
currentTab = cctab;
}
Note that doing inline event handler attributes is so 1999, but assuming you're sticking with it for whatever reason you don't need the javascript: in onClick="javascript:toggleRow(cctab);". (Just say onClick="toggleRow(cctab);")
First you need to store the old row somewhere.
What you've got is a system where you're using <element onclick="..."> to pass the id of the current element into the controller that shows or hides the row.
But if you look at that, what you're missing is a way of telling what the last open row was.
So what your code will need is a central object, or variables which store the old element and the new element.
How you do this is up to you, but if you did something like this:
var table_rows = { current : null /* or set a default */, previous : null };
function rowController (cctab) {
var newRow = document.getElementById(cctab);
if (newRow === table_rows.current) { toggleRow(newRow); }
else {
table_rows.previous = table_rows.current;
table_rows.current = newRow;
showRow(table_rows.current);
hideRow(table_rows.previous);
}
}
Note:
This deals with elements directly, so you don't have to do getById in your functions;
that's handled one time, and then that element is passed around and saved and checked against.
It assumes that the click is happening on the row itself, and not on anything inside of the row;
that's a separate issue that your code has.
Unless it's obvious and easy to click on the row, and not the cells inside of the row, it's difficult to tell how you want users to be able to open and close rows.
What I mean is if only the table-row has an onclick, and somebody clicks on a table-column, then then onclick isn't going to fire.

Is it possible to change the action of Bootstrap popovers based on screen width?

I asked this question regarding changing the position of a bootstrap popover depending on the size of the screen.
The answer was great - however I also now want to change the action for popovers (so it's on click for mobile) as well as the location, and am having difficulty re-factoring the code. This is what I have:
$(document).ready(function(){
$('#my_list li').popover({
placement: wheretoplace
});
});
function wheretoplace(){
var width = window.innerWidth;
if (width<500) return 'below';
return 'left';
}
How would I amend the wheretoplace function to return two things: the placement value along with a trigger value? I've got the existing stuff in a jsFiddle.
Edit - I've amended my jsFiddle above to show the complete solution, adding a click event to #James' answer below.
If you are trying to return two values from the function, try assigning them as properties of an object and then return that object.
eg.
function wheretoplace(){
var data = {};
var width = window.innerWidth;
if (width<500)
{
data.placement = 'below';
}
else
{
data.placement = 'left';
}
data.trigger = "myEvent";
return data;
}
Then in the function calling wheretoplace:
$(document).ready(function(){
$('#my_list li').popover({
placement: wheretoplace().placement,
trigger: wheretoplace().trigger
});
});
Is this what you are trying to do?
EDIT: In Response to the comment below:
As with the jsFiddle demo
By assigning the trigger as "manual" on document ready, you are then able to call $(element).popover("toggle") in a click handler which will toggle the appearance of the popover.

Categories