I've got a dropdown box with a bunch of options for an image. Each image has an id in the database. The images are located in foo/images/ and are named after their id's in the database (21.gif, 32.png etc). The problem I'm having is testing to see if which extension works and use that one. Here's my code so far, i recently added the $.get(lnk) portion as a bad attempt, I'm new to Jquery. My thought process is if it was the right extension it would return true and be fine, and if it failed have it repeat until it returned true. Any way to do this? explain like im five
<SELECT NAME=IMG1 onchange=\'
this.form.SIGN_NFPA.selectedIndex = 0;
var id = this.options[this.selectedIndex].value
var exts = ["png", "gif", "jpg", "jpeg"];
var count = 0;
var lnk = (id) ? "foo/images/"+id+"."+exts[count] : "blank.gif";
window.document.IMG1.src = lnk;
$.get(lnk)
.done(function() {
return true;
}).fail(function() {
count = count + 1;
lnk = (id) ? "foo/images/"+id+"."+exts[count] : "blank.gif";
})
return true;
\'>
I've commented the code to help make it more readable.
$( "#select" ).on( "change", function () {
// grab the value for the select box
var val = $( this ).val();
// file extensions
var exts = [ "gif", "png", "jpg", "jpeg" ];
// set img = false, used to detect if img exists.
var img = false;
// set i = 0, stops the while looping forever
var i = 0;
var url;
// while image is false and there are more extensions to try
while ( !img && i < exts.length ) {
// set the url
url = "foo/images/" + val + "." + exts[ i ];
// build and send a request to see i the image exists.
var req = new XMLHttpRequest();
req.open( 'GET', url, false );
req.send();
// set img to the request status
img = req.status == 200;
// add 1 to i
i++;
}
// if no url, set url to "blank.gif"
url = img ? url : "blank.gif";
// set the image src attribute.
$( "#" + val ).attr( "src", url );
} );
I hope this helps.
Related
Everything was working fine on home page: http://kikidesign.net/dev/mcdowell/, especially the stores section and the opening hours in the footer at the bottom. However, when I went to the http://kikidesign.net/dev/mcdowell/stores/, the stores were not loading. It means that the javascript for this stores are not loading. But when I checked the console log, it shows that the javascript file are there and I found out that when I take out the other javascript file (the opening hours.js), it loads fine but when I put it back, the stores doesn't load. I don't understand why both files were working fine on the home page but no so on the stores page. How do I fix it? I even combined two files together and it loads fine on the home page but not so on the store page. Additionally, the stores section has mixitup plugin with jquery.mixitup.min.js.
Stores files
jquery-custom-scripts.js
( function( $ ) {
$( document ).ready(function() {
var dropdownFilter = {
// Declare any variables we will need as properties of the object
$filters: null,
$reset: null,
groups: [],
outputArray: [],
outputString: '',
// The "init" method will run on document ready and cache any jQuery objects we will need.
init: function(){
var self = this; // As a best practice, in each method we will asign "this" to the variable "self" so that it remains scope-agnostic. We will use it to refer to the parent "dropdownFilter" object so that we can share methods and properties between all parts of the object.
self.$filters = $('#Filters');
self.$reset = $('#Reset');
self.$container = $('#isotope-list');
self.$filters.find('fieldset').each(function(){
var $this = $(this);
self.groups.push({
$buttons : $this.find('.filter'),
$inputsSelect : $this.find('select'),
$inputsText : $this.find('input[type="text"]'),
active : ''
});
});
self.bindHandlers();
},
// The "bindHandlers" method will listen for whenever a select is changed.
bindHandlers: function(){
var self = this;
// Handle select change
self.$filters.on('click', '.filter', function(e){
e.preventDefault();
var $button = $(this);
// If the button is active, remove the active class, else make active and deactivate others.
$button.hasClass('active2') ?
$button.removeClass('active2') :
$button.addClass('active2').siblings('.filter').removeClass('active2');
self.parseFilters();
});
// Handle dropdown change
self.$filters.on('change', function(){
self.parseFilters();
});
// Handle key up on inputs
self.$filters.on('keyup', 'input[type="text"]', function() {
var $input = $(this);
console.log($input.val());
$input.attr('data-filter', '[class*="'+$input.val().replace(/ /, '-')+'"]');
if ($input.val() == '')
$input.attr('data-filter', '');
console.log($input.attr('data-filter'));
self.parseFilters();
});
// Handle reset click
self.$reset.on('click', function(e){
e.preventDefault();
self.$filters.find('.filter').removeClass('active2');
self.$filters.find('.show-all').addClass('active2');
self.$filters.find('select').val('');
self.$filters.find('input[type="text"]').val('').attr('data-filter', '');
self.parseFilters();
});
},
// The parseFilters method pulls the value of each active select option
parseFilters: function(){
var self = this;
// loop through each filter group and grap the value from each one.
for(var i = 0, group; group = self.groups[i]; i++){
var activeButtons = group.$buttons.length ? group.$buttons.filter('.active2').attr('data-filter') || '' : '';
var activeSelect = group.$inputsSelect.length ? group.$inputsSelect.val() || '' : '';
var activeText = group.$inputsText.length ? group.$inputsText.attr('data-filter') : '';
group.active = activeButtons+activeSelect+activeText;
console.log(group.active);
}
self.concatenate();
},
// The "concatenate" method will crawl through each group, concatenating filters as desired:
concatenate: function(){
var self = this;
self.outputString = ''; // Reset output string
for(var i = 0, group; group = self.groups[i]; i++){
self.outputString += group.active;
}
// If the output string is empty, show all rather than none:
!self.outputString.length && (self.outputString = 'all');
console.log(self.outputString);
// ^ we can check the console here to take a look at the filter string that is produced
// Send the output string to MixItUp via the 'filter' method:
if(self.$container.mixItUp('isLoaded')){
self.$container.mixItUp('filter', self.outputString);
}
}
};
// On document ready, initialise our code.
$(function(){
// Initialize dropdownFilter code
dropdownFilter.init();
// Instantiate MixItUp
$('#isotope-list').mixItUp({
controls: {
enable: false // we won't be needing these
},
callbacks: {
onMixFail: function(){
alert('No items were found matching the selected filters.');
}
}
});
});
$('.btn-clear').on('click', function(event) {
event.preventDefault();
$(this).prev().val("").change();
});
$('select').change(function() {
if ($(this).val() == "") {
$(this).next().hide('.btn-hide');
} else {
$(this).next().show('.btn-hide');
}
});
});
} )( jQuery );
Opening hours js file
( function( $ ) {
$( document ).ready(function() {
var currentDate = new Date();
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Weekday";
weekday[2] = "Weekday";
weekday[3] = "Weekday";
weekday[4] = "Weekday";
weekday[5] = "Weekday";
weekday[6] = "Saturday";
var currentDay = weekday[currentDate.getDay()];
var currentDayID = "#" + currentDay; //gets todays weekday and turns it into id
$(currentDayID).toggleClass("today"); //this works at hightlighting today
});
$( document ).ready(function() {
var dayOfWeek = (new Date).getDay();
var hours = ["Today: 9:00am to 6:00pm", // Sunday
"Today: 8:00am to 9:00pm", // Monday
"Today: 8:00am to 9:00pm", // Tuesday
"Today: 8:00am to 9:00pm", // Wednesday
"Today: 8:00am to 9:00pm", // Thursday
"Today: 8:00am to 9:00pm", // Friday
"Today: 8:00am to 5:00pm"]; // Saturday
var todaysHours = hours[dayOfWeek];
document.getElementById("hours").innerHTML = todaysHours;
});
} )( jQuery );
Console is giving you the error of your code:
Uncaught TypeError: Cannot set property 'innerHTML' of null
As you're trying to do at line 212:
document.getElementById("hours").innerHTML = todaysHours;
Are you sure that #hours element exist? I can't find it in your HTML, so you're trying to do something with an element that doesn't exist.
You should do in order to avoid that problem:
var DOMhours = document.getElementById("hours")
if (DOMhours) DOMhours.innerHTML = todaysHours
If you want to do that after the stores are loaded, you should be sure that the stores are loaded and, after the stores are loaded and you've appended them to the HTML, get the #hours element and put the innerHTML that you want. But always is a good idea to check before if the element is there to avoid those errors. :)
You are trying to set the property of a DOM element that doesn't exist.
Line 212:
document.getElementById("hours").innerHTML = todaysHours;
You can check the browser's console for errors like these by pressing F12.
I want to make a Google chrome extension that when i click on it.
then the variable i will go up once and when i click again i want it to go up once more.
when Variable i equals 3 then i want to to set to 0 again.
I want to make a sort of switch.
BACKGROUND.JS
var i = 0;
chrome.browserAction.onClicked.addListener(function(activeTab) {
i = i + 1
if (i == 1) {
var newURL = "http://www.website1.com";
chrome.tabs.create({ url: newURL });
var newURL = "http://www.website2.com";
chrome.tabs.create({ url: newURL });
var newURL = "http://www.website3.com";
} elseif (i == 2) {
chrome.tabs.close()
} else {
var i = 0
}
});
when i click on my Extension notification then it doesnt do anything at all.
and i think the chrome.tabs.close also doensnt work.
var i = 0
Should be outside the function
I found the following script online that makes your website load content with AJAX.
Everything works fine, but it also reload my music player that has to stay when clicking a link.
// Ajaxify
// v1.0.1 - 30 September, 2012
// https://github.com/browserstate/ajaxify
(function(window,undefined){
// Prepare our Variables
var
History = window.History,
$ = window.jQuery,
document = window.document;
// Check to see if History.js is enabled for our Browser
if ( !History.enabled ) {
return false;
}
// Wait for Document
$(function(){
// Prepare Variables
var
/* Application Specific Variables */
contentSelector = '#content,article:first,.article:first,.post:first',
$content = $(contentSelector).filter(':first'),
contentNode = $content.get(0),
$menu = $('#menu,#nav,nav:first,.nav:first').filter(':first'),
activeClass = 'active selected current youarehere',
activeSelector = '.active,.selected,.current,.youarehere',
menuChildrenSelector = '> li,> ul > li',
completedEventName = 'statechangecomplete',
/* Application Generic Variables */
$window = $(window),
$body = $(document.body),
rootUrl = History.getRootUrl(),
scrollOptions = {
duration: 800,
easing:'swing'
};
// Ensure Content
if ( $content.length === 0 ) {
$content = $body;
}
// Internal Helper
$.expr[':'].internal = function(obj, index, meta, stack){
// Prepare
var
$this = $(obj),
url = $this.attr('href')||'',
isInternalLink;
// Check link
isInternalLink = url.substring(0,rootUrl.length) === rootUrl || url.indexOf(':') === -1;
// Ignore or Keep
return isInternalLink;
};
// HTML Helper
var documentHtml = function(html){
// Prepare
var result = String(html)
.replace(/<\!DOCTYPE[^>]*>/i, '')
.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
.replace(/<\/(html|head|body|title|meta|script)\>/gi,'</div>')
;
// Return
return $.trim(result);
};
// Ajaxify Helper
$.fn.ajaxify = function(){
// Prepare
var $this = $(this);
// Ajaxify
$this.find('a:internal:not(.no-ajaxy)').click(function(event){
// Prepare
var
$this = $(this),
url = $this.attr('href'),
title = $this.attr('title')||null;
// Continue as normal for cmd clicks etc
if ( event.which == 2 || event.metaKey ) { return true; }
// Ajaxify this link
History.pushState(null,title,url);
event.preventDefault();
return false;
});
// Chain
return $this;
};
// Ajaxify our Internal Links
$body.ajaxify();
// Hook into State Changes
$window.bind('statechange',function(){
// Prepare Variables
var
State = History.getState(),
url = State.url,
relativeUrl = url.replace(rootUrl,'');
// Set Loading
$body.addClass('loading');
// Start Fade Out
// Animating to opacity to 0 still keeps the element's height intact
// Which prevents that annoying pop bang issue when loading in new content
$content.animate({opacity:0},800);
// Ajax Request the Traditional Page
$.ajax({
url: url,
success: function(data, textStatus, jqXHR){
// Prepare
var
$data = $(documentHtml(data)),
$dataBody = $data.find('.document-body:first'),
$dataContent = $dataBody.find(contentSelector).filter(':first'),
$menuChildren, contentHtml, $scripts;
// Fetch the scripts
$scripts = $dataContent.find('.document-script');
if ( $scripts.length ) {
$scripts.detach();
}
// Fetch the content
contentHtml = $dataContent.html()||$data.html();
if ( !contentHtml ) {
document.location.href = url;
return false;
}
// Update the menu
$menuChildren = $menu.find(menuChildrenSelector);
$menuChildren.filter(activeSelector).removeClass(activeClass);
$menuChildren = $menuChildren.has('a[href^="'+relativeUrl+'"],a[href^="/'+relativeUrl+'"],a[href^="'+url+'"]');
if ( $menuChildren.length === 1 ) { $menuChildren.addClass(activeClass); }
// Update the content
$content.stop(true,true);
$content.html(contentHtml).ajaxify().css('opacity',100).show(); /* you could fade in here if you'd like */
// Update the title
document.title = $data.find('.document-title:first').text();
try {
document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<','<').replace('>','>').replace(' & ',' & ');
}
catch ( Exception ) { }
// Add the scripts
$scripts.each(function(){
var $script = $(this), scriptText = $script.text(), scriptNode = document.createElement('script');
if ( $script.attr('src') ) {
if ( !$script[0].async ) { scriptNode.async = false; }
scriptNode.src = $script.attr('src');
}
scriptNode.appendChild(document.createTextNode(scriptText));
contentNode.appendChild(scriptNode);
});
// Complete the change
if ( $body.ScrollTo||false ) { $body.ScrollTo(scrollOptions); } /* http://balupton.com/projects/jquery-scrollto */
$body.removeClass('loading');
$window.trigger(completedEventName);
// Inform Google Analytics of the change
if ( typeof window._gaq !== 'undefined' ) {
window._gaq.push(['_trackPageview', relativeUrl]);
}
// Inform ReInvigorate of a state change
if ( typeof window.reinvigorate !== 'undefined' && typeof window.reinvigorate.ajax_track !== 'undefined' ) {
reinvigorate.ajax_track(url);
// ^ we use the full url here as that is what reinvigorate supports
}
},
error: function(jqXHR, textStatus, errorThrown){
document.location.href = url;
return false;
}
}); // end ajax
}); // end onStateChange
}); // end onDomLoad
})(window); // end closure
Let me explain it a little bit better.
The website has a music player that plays music while you are visiting the website, so clearly the music is not ment to stop whenever you click on a link.
This script works perfectly but it does refresh the whole page (using ajax) AND it is refreshing the music player.
There also is another script that comes with this one for changing the url and title ...
Thanks in advance, Greets
use the statechangecomplete event.
$(window).on('statechangecomplete', function(e, eventInfo){
//your code
})
In my CKEditor I removed the 'linkType' and 'protocol' inputs of the link dialog.
CKEDITOR.on( 'dialogDefinition', function( ev )
{
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if ( dialogName == 'link' )
{
var infoTab = dialogDefinition.getContents( 'info' );
infoTab.remove( 'linkType' );
infoTab.remove( 'protocol' );
}
});
However, evertype I type in something like https://google.com as soon as I type in the 'g' the https:// gets removed.
I checked the output and it always says http:// disregarding the input.
How can I turn this stupid behaviour off?
After much research, debugging and tweaking, I've finally managed to pull this off!!!
Here's how I do it:
CKEDITOR.on('dialogDefinition', function(e) {
// NOTE: this is an instance of CKEDITOR.dialog.definitionObject
var dd = e.data.definition;
if (e.data.name === 'link') {
dd.minHeight = 30;
// remove the unwanted tabs
dd.removeContents('advanced');
dd.removeContents('target');
dd.removeContents('upload');
// remove all elements from the 'info' tab
var tabInfo = dd.getContents('info');
while (tabInfo.elements.length > 0) {
tabInfo.remove(tabInfo.elements[0].id);
}
// add a simple URL text field
tabInfo.add({
type : 'text',
id : 'urlNew',
label : 'URL',
setup : function(data) {
var value = '';
if (data.url) {
if (data.url.protocol) {
value += data.url.protocol;
}
if (data.url.url) {
value += data.url.url;
}
} else if (data.email && data.email.address) {
value = 'mailto:' + data.email.address;
}
this.setValue(value);
},
commit : function(data) {
data.url = { protocol: '', url: this.getValue() };
}
});
}
});
Here's how I removed the protocol in v4.5.1:
CKEDITOR.on('dialogDefinition', function(ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if (dialogName === 'link') {
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('protocol');
var url = infoTab.get('url');
url.onKeyUp = function(){};
url.setup = function(data) {
this.allowOnChange = false;
if (data.url) {
var value = '';
if (data.url.protocol) {
value += data.url.protocol;
}
if (data.url.url) {
value += data.url.url;
}
this.setValue(value);
}
this.allowOnChange = true;
};
url.commit = function(data) {
data.url = { protocol: '', url: this.getValue() };
};
}
});
I'm afraid there's no way to change it. You have to manually edit a few lines of the code to make it working your way.
I recently found a way to hide the Link Type so you don't have to remove it totally. Set the style to display: none like the following:
infoTab.get( 'linkType' ).style = 'display: none';
I think it works for the Protocol as well, but I haven't tested it. I answered the same question here
Hope this helps someone!
For the lazy people like me, just do a quick core file hack:
open plugins/link/dialogs/link.js
in the minimized version find d=/^(http|https|ftp|news):\/\/(?=.)/i.exec(b);
remove http|https|ftp|
save file, upload it to your server
If it does not work after reload, this might be a cache problem. Open browser in private mode, navigate to your ckeditor and try it again. Good luck.
How do you implement deep linking on a page so when the user comes that that page from an external link, that fancybox modal is initiated. I'm new to JS/Jquery
I was looking for the same thing this morning and found your question as well as a forum post that has an answer.
(function()
{
var qs = location.search.slice( 1 ),
params = qs.match( /&?ab=(\d+)\|(\d+)/ );
if( params )
page( Number( params[ 1 ] ), Number( params[ 2 ] ) );
})();
"Then if you link to that page passing your two numeric parameters in this form:
concert.html?ab=1|5
It should have the stunning effect of calling page(1, 5); when the page loads. "
http://www.webdeveloper.com/forum/showthread.php?t=247899
Hope it helps - it helped me. :)
I just solved it for myself with fancybox2 and url hashes.
You can use Fancybox callbacks to set and unset hashes.
I used data attributes in the img tag to store img identifiers.
Then you can check for a hash in the url at pageload, get the index and open the fancybox with the given index.
var option = {
afterLoad: function(links) {
var title = links.element.attr('data-my-img');
location.hash = title;
},
afterClose: function() {
location.hash = '';
}
},
hash = location.hash.substr(1),
gallery = $('.fancybox');
if(hash.length > 0){
//id
var i = null;
gallery.each(function(index) {
var o = $(this).attr('data-my-img');
if($(this).attr('data-my-img') == hash){
i = index;
return;
}
});
if(i != null){
option.index = i;
$.fancybox.open(gallery, option);
}
}
gallery.fancybox(option);