Building a new site and trying to reuse a JavaScript from the current site that change image on hover. I have a hard time to understand JavaScript so I hope someone can help me to see what I'm missing or doing wrong.
The current site (where I copied from) has many more script running and I don't know if some other script is missing. I have tried to change the initializing part of the script to fit the new site. Please have a look at the puzzlepiece on the current page. http://www.collyfiltreringsteknik.se.
I have got the script running to a point where it adds the four "quad" divs but the mouseover and click function does not work.
This is the html code
<div id="companyvalues" class="clearfix">
<div class="valueimage"></div>
</div>
The jQuery part
(function($){
$.fn.extend({
companyvalues: function(kwargs) {
var defaults = {
static_base:''
};
var options = $.extend(defaults, kwargs);
return this.each(function() {
var obj = $(this);
var div = $('div', obj);
var topleft = $('<div class="quad topleft" data-image="i0000" data-href="/grundpelare/tillganglighet/"></div>');
var topright = $('<div class="quad topright" data-image="i0003" data-href="/grundpelare/konkurrenskraft/"></div>');
var bottomleft = $('<div class="quad bottomleft" data-image="i0002" data-href="/grundpelare/miljoforbattring/"></div>');
var bottomright = $('<div class="quad bottomright" data-image="i0001" data-href="/grundpelare/kostnadsreducering/"></div>');
obj.prepend(bottomright);
obj.prepend(bottomleft);
obj.prepend(topright);
obj.prepend(topleft);
var divs = $('div.quad', obj);
$([ '/uploads/pages/varden_0000_yellow.png',
'/uploads/pages/varden_0001_red.png',
'/uploads/pages/varden_0002_green.png',
'/uploads/pages/varden_0003_blue.png'
]).preload({base_url:options.static_base});
divs.mouseover(function(event) {
var item = $(this);
var data_image = item.attr('data-image');
div.addClass(data_image);
event.preventDefault();
event.stopPropagation();
});
divs.mouseout(function(event) {
var item = $(this);
div.removeClass('i0000');
div.removeClass('i0001');
div.removeClass('i0002');
div.removeClass('i0003');
event.preventDefault();
event.stopPropagation();
});
divs.click(function(event) {
var item = $(this);
var href = item.attr('data-href')
document.location.href=href;
event.preventDefault();
event.stopPropagation();
});
});
}
});
})(jQuery);
Initializing the script.
$(document).ready(function() {
$('#companyvalues').companyvalues();
});
Related
This question already has answers here:
jQuery .on() event doesn't work for dynamically added element
(3 answers)
Closed 4 years ago.
I have this problem in JQuery and I can't seem to get past this issue.
I have a dynamically generated list of Li elements, and for each Li element I want to attach an On Hover so that a dropdown shows below the Li element. The catch is the Li elements are generated dynamically.
I have tried using .on("hover"), but nothing triggeres the event. The following is my code.
//On Init
$( document ).ready(function() {
generateList();
$(".app").on("hover", function () {
console.log('test'); //Does not trigger
});
$(".app").on("mouseenter", function () {
console.log('test'); //Does not trigger
});
});
//Load JSON file to generate app listing
function generateList(){
//Load JSON file
$.getJSON('json/adapters.json', function (json) {
var listCol = 5;
var ul = $('#container-apps');
//Generate app list from adapters.JSON
json.adapters.forEach(function (adapter) {
//Count adapter for no result function
adapterCount += 1;
var link = adapter.link;
var git = adapter.git;
var img = adapter.image;
var name = adapter.name;
//Appending the HTML elements
//List element
var li = $("<li>").attr("class", "app").appendTo(ul);
var a = $("<a>").attr({
"href": "javascript:void(0);",
"target":"_blank",
"class":"app-link",
}).appendTo(li);
var image = $("<img>").attr("src", img).appendTo(a);
var label = $("<div>").attr("class", "item-name black-font").html(name).appendTo(a);
//Hover element
var hoverContainer = $("<div>").attr("class", "hoverContainer").appendTo(li);
var hoverUL = $("<ul>").appendTo(hoverContainer);
var hoverPageLi = $("<li>").appendTo(hoverUL);
var hoverPageA = $("<a>").attr({"href": link, "target":"_blank", "class":"app-link"}).html("SDK").appendTo(hoverPageLi);
var hoverGitLi = $("<li>").appendTo(hoverUL);
var hoverGitA = $("<a>").attr({"href": git, "target":"_blank", "class":"app-link"}).html("Github").appendTo(hoverGitLi);
});
//Generate dummy box for responsive
for (var i = 0; i < (listCol); i++) {
$('<li class="item flex-dummy"></li>').appendTo(ul);
}
});
}
$(function () {
$(".app").hover(){
console.log('test'); //Does not trigger
}
})
Try this syntax:
$("body").on("click", ".app", function(){
//do something
});
In the mobile version on my form appears 'Close' button.
Unfortunately, it does not work. I see a normal button, but when I click there is no reaction. In the javascript I load the file form-with-button.html to render form content in my all .html files.
<div id="form-with-button">
</div>
and use javascript to show and close.
//Onload show header and footer content
$("#header").load('header.html', function(){
$('#nav').affix({
offset: {top: $('#header').height()-$('#nav').height()}
});
});
$("#footer").load('footer.html');
$("#contact").load('footer-contact.html');
$("#form-with-button").load('form-with-button.html');
// Sticky Buttons Show Hide
$("#fix-quote, #fix-contact").on("click", function() {
var body = $("body");
var openPos= ["",""];
var id = $(this).attr("id");
var content = $("#"+id+"-content");
var property = (content.attr("class").toString().indexOf("left") > -1)? "left": "right";
if (!body.hasClass("bd_"+id)) {
openPos= [0,380]
var ele = $(this);
body.addClass("bd_"+id)
setTimeout(function(){
body.on("click.fix",function(ev) {
if($(ev.target).closest(".fixed-container").length == 0){
$(ele).click()
}
});
},10);
} else {
body.removeClass("bd_"+id).off("click.fix");
}
content.css("top","").show().css(property, openPos[0]);
$(this).css(property, openPos[1]);
});
// Mobile Requests Showhide
$("#fix-quote-mob, #fix-contact-mob").on("click", function() {
var id = $(this).attr("id").slice(0,-4);
var content = $("#"+id+"-content");
content.show()
setTimeout(function(){
content.css("top",0)
},10)
});
$(".fix-contact-close").on("click", function() {
var content = $(this).closest(".fixed-container");
content.css("top","").delay(400).hide(0);
});
Please help, why my button does not work?
You are trying to add a handler to an element created in a dynamic way, so you need to refactor your code in order to make it work:
$(document).on("click", ".fix-contact-close", function() {
var content = $(this).closest(".fixed-container");
content.css("top","").delay(400).hide(0);
});
I have tried searching for what I am trying to accomplish, however I have not found what I am looking for.
I am looking to create a Next and Previous button inside the content of the Spry Accordion provided with Dreamweaver CS6. I have searched the SpryAccordion.js and found this code below:
Spry.Widget.Accordion.prototype.openNextPanel = function()
{
return this.openPanel(this.getCurrentPanelIndex() + 1);
};
Spry.Widget.Accordion.prototype.openPreviousPanel = function()
{
return this.openPanel(this.getCurrentPanelIndex() - 1);
};
So I attempted to do this with "#acc-step-1-next" being my "Next" button in Panel 1.
<script>
$(document).ready(function(){
$("#acc-step-1-next").click(function(){
Spry.Widget.Accordion.prototype.openNextPanel = function(){
return ('#Accordian1').openPanel(this.getCurrentPanelIndex() + 1);
};
});
});
</script>
I was wondering if doing it this way might make it easy! How would I go about applying this? Would this work or not?
Also, with the "Next" button, could I just make it ".acc-step-next" and use it universally, instead of individually assigning new ID's?
EDIT:
Sorry, yes I read your answer incorrectly. I have tried searching for the init property, however have had no success.
This is what starts in the Accordion JS file:
(function() { // BeginSpryComponent
if (typeof Spry == "undefined") window.Spry = {}; if (!Spry.Widget) Spry.Widget = {};
Spry.Widget.Accordion = function(element, opts)
{
this.element = this.getElement(element);
this.defaultPanel = 0;
this.hoverClass = "AccordionPanelTabHover";
this.openClass = "AccordionPanelOpen";
this.closedClass = "AccordionPanelClosed";
this.focusedClass = "AccordionFocused";
this.enableAnimation = true;
this.enableKeyboardNavigation = true;
this.currentPanel = null;
this.animator = null;
this.hasFocus = null;
this.previousPanelKeyCode = Spry.Widget.Accordion.KEY_UP;
this.nextPanelKeyCode = Spry.Widget.Accordion.KEY_DOWN;
this.useFixedPanelHeights = false;
this.fixedPanelHeight = 0;
Spry.Widget.Accordion.setOptions(this, opts, true);
if (this.element)
this.attachBehaviors();
};
Which I added this after, but still no luck:
var acc_next = document.getElementById("acc-step-next");
var acc_prev = document.getElementById("acc-step-prev");
$("acc_next").click(function(){
accordion.openNextPanel();
});
$("acc_prev").click(function() {
accordion.openPreviousPanel();
});
I have never worked with Spry.Widget.Accordion, but I would try something like the following.
Search for the code, where your accordion is initialized, it should look something like that:
var accordion = new Spry.Widget.Accordion("Accordian1",{});
And add this just below:
$(".acc-step-next").click(function(){
accordion.openNextPanel();
});
Together it could look something like that:
<script type="text/javascript">
$(document).ready(function(){
var accordion = new Spry.Widget.Accordion("Accordian1",{});
// Add a click handler to all buttons with the class 'acc-step-next' (yes you can do that)
$(".acc-step-next").click(function(){
// when the button is clicked, call the openNextPanel method of the accordion instance we saved above
accordion.openNextPanel();
});
});
</script>
So I am working on this but of jQuery that gets the element id through a click event. This then triggers a function that acts like the deprecated .toggle()- it slides an element down on the fist click and slides that element up on the second click. However, there is a bug that causes the element to slide up and down the amount of times that it has been clicked on. For instance, if this is the second time I use the .clickToggle function, the element (table) slides up and down twice before settling, and so on. I suspect it has something to do with the event object, e, tracking the number of clicks-- i.e. I probably shouldn't set id = e.target.id-- but I'm not sure how to fix while still getting the relevant element id that I need.
Here is the relevant clickToggle plug in (courtesy of an answer here on stackoverflow).
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
Here is the buggy code that fits the above description.
$(document).click(function(e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/);
//clickToggle the individual table
$('#showTable' + strId).clickToggle(function () {
$('#table' + strId).slideDown();
$('#table' + strId).load('files.php');
},
function () {
$('#table' + strId).slideUp();
});
});//close mousemove function
Any help would be much appreciated. Thanks.
The problem is that you're registering a new click handler for the element each time you invoke clickToggle:
this.click(function() {...
On each subsequent click, you add another handler, as well as invoking all previous handlers. Bleagh.
Better to be straightforward: (DEMO)
var showTable = function($table) {
$table.slideDown();
$table.load('files.php');
$table.removeClass('hidden');
};
var hideTable = function($table) {
$table.slideUp();
$table.addClass('hidden');
};
$(document).click(function (e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/)[0];
var $table = $('#table' + strId);
if ($table.hasClass('hidden')) {
showTable($table);
} else {
hideTable($table);
}
});
var toogleDelay = 500;
var closeTimeout = null;
$(">ul>li", $nav).hover(function () {
var $this = $(this);
if(closeTimeout) {
clearTimeout(closeTimeout);
}
var openMenuCallback = function() {
$this.addClass("hover");
};
window.setTimeout(openMenuCallback, toogleDelay);
}, function () {
var $this = $(this);
var closeMenuCallback = function() {
$this.removeClass("hover");
};
closeTimeout = window.setTimeout(closeMenuCallback, toogleDelay);
});
I use this snippet to open and close a multidropdown-menu and I want the menu to fade in and out with a 0.5s delay. I also added a cleartimeout to the mouseover part of the jquery hover function, so that the menu does not close if somebody (accidently) leaves the menuarea and enters it again within the 0.5s. This all works fine, but I now have the problem, because there is more than just one dropdown, that the closeTimeout of lets say the first dropdown gets cleared, if I move the mouse from the first directly to the second dropdown and I now have both dropdown-elements open. How must I rewrite the code, so that every dropdown has its own closeTimeout and at the same time I am still able to clear the timeout in the mouseover part of the hover function.
thx
sub
You could store the timer's id in the element's data. Something like
var $this = $(this);
var closeMenuCallback = function() {
$this.removeClass("hover");
$this.removeData("timerid");
};
var closeTimeout = window.setTimeout(closeMenuCallback, toogleDelay);
$this.data("timerid", closeTimeout);
and then check it with
var $this = $(this);
var closeTimeout = $this.data("timerid");
if(closeTimeout) {
clearTimeout(closeTimeout);
$this.removeData("timerid");
}
I know this isn't part of the question but I like the CSS approach to this.
http://webdesignerwall.com/tutorials/css3-dropdown-menu
there are a number of examples for this. some multilevel some not.