Change javascript function - javascript

I have a function in theme.js file
$('.open_copy').click(function(){
var that = $(this);
var copy = that.prev();
that.parents('.asset').find('.cover').click();
copy.css('opacity', 0).show();
if (copy.children('.copy_content').data('jsp')) {
copy.children('.copy_content').data('jsp').destroy();
}
var height = copy.children('.copy_content').css({height: ''}).height();
if (height < that.parents('.asset').height() - 37) {
var top = (that.parents('.asset').height() - height)/2;
top = top < 37 ? 37 : top;
copy.children('.copy_content').css({'margin-top': top});
} else {
copy.children('.copy_content').css({'margin-top': '', height: that.parents('.asset').height() - 37}).jScrollPane();
}
if (!that.parents('.asset').find('.close_copy').length) {
that.prev().append('Close');
}
copy.animate({ 'opacity' : 1 }, 500);
that.fadeOut(500);
return false;
});
I need to change opacity value to 0.9 but i don't have access to the theme.js file. There is any way i can change/alter this function by adding a function in the html page?
copy.animate({ 'opacity' : 1 }, 500);

Yes. You can remove the click handler that code sets up, and then add your own with identical code except for the 1 => 0.9 change.
To remove that code's click handler (and all others), use off:
$('.open_copy').off('click');
...and then of course add your own, new click handler.
So in total, then, you'd want this code (after the script tag including theme.js, so this code runs after that code):
$('.open_copy').off('click').click(function(){ // <== Changed
var that = $(this);
var copy = that.prev();
that.parents('.asset').find('.cover').click();
copy.css('opacity', 0).show();
if (copy.children('.copy_content').data('jsp')) {
copy.children('.copy_content').data('jsp').destroy();
}
var height = copy.children('.copy_content').css({height: ''}).height();
if (height < that.parents('.asset').height() - 37) {
var top = (that.parents('.asset').height() - height)/2;
top = top < 37 ? 37 : top;
copy.children('.copy_content').css({'margin-top': top});
} else {
copy.children('.copy_content').css({'margin-top': '', height: that.parents('.asset').height() - 37}).jScrollPane();
}
if (!that.parents('.asset').find('.close_copy').length) {
that.prev().append('Close');
}
copy.animate({ 'opacity' : 0.9 }, 500); // <== Changed
that.fadeOut(500);
return false;
});
You'll want to check for side effects (for instance, if there's other code that also sets up click handlers on those elements, since the code above will remove them, too).

Javascript support override of variables and methods.
You should declare an overriding JS script AFTER import of Theme.js file.
So, you can exactly copy/paste that function changing only the values you need to.
Note that, as that function is an event binding, you may need to unbind the onclick event first.

Related

If/Else jQuery is breaking my script

I am trying to set-up an if/else statement that if a class exists then the var num will equal 100, if the class does not exist then var num will equal 55. num is then used to understand how many pixels the screen will be offset. Any help will be appreciated as Javascript is one of my weak points.
// Add scrollspy to <body>
$('body').scrollspy({target: ".navbar", offset: 55});
// Checks to see if navbar is affixed or not
if (($(".affix-top")[0]){) {
num = 100;
} else {
num = 55;
}
// Add smooth scrolling on all links inside the navbar
$(".navbar-lower a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (300) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top - num
}, 300, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
This is difficult to read.
if (($(".affix-top")[0]){) {
num = 100;
} else {
num = 55;
}
It can be simplified to just this, because anything matched is true.
var num = $(".affix-top").length ? 100 : 55;
That will not work if the script runs before the rest of the HTML page has loaded.
<script type="application/javascript"> $(".affix-top").length > 0; // false </script>
<div class="affix-top"></div>
<script type="application/javascript"> $(".affix-top").length > 0; // true </script>
So wrap everything in a jQuery ready block.
jQuery(document).ready(function(){
var num = $(".affix-top").length ? 100 : 55;
//....... insert more code here
});
You dont need the extra brackets. Also, just check .length to see if an element exists. It's subjective but IMO it makes it easier to read.
if ( $(".affix-top").length ) {
num = 100;
} else {
num = 55;
}
You have a { where it doesn't belong
if (($(".affix-top")[0]){) {
should be
if (($(".affix-top")[0])) {

Directive on click event listener and $postLink click event listener not working together

i am using angular1's component design to build this application. i have made a directive with does the ripple effect on a button when user clicks on it. this is a common behaviour so i have taken it in the directive.
now i want to add another event listener to the same button from the component controllers $postLink() hook which causes directive event listener to fail in execution.
how to solve this issue. i want both events listened.
below is my ripple effect directive. i am using commonjs to load the modules so don't be bothered by that.
var app=require('../../../../Development/Assets/Js/appConfig');
app.directive('wave',waveConig);
waveConig.$inject=['$compile','$timeout'];
function waveConig($compile,$timeout){
return{
restrict:'A',
link:waveLink
};
function waveLink(scope,elem,attr){
var waveColor = attr.color;
elem.unbind('mousedown').bind('mousedown', function (ev) {
var el = elem[0].getBoundingClientRect();
var top = el.top;
var left = el.left;
var mX = ev.clientX - left;
var mY = ev.clientY - top;
var height = elem[0].clientHeight;
var rippler = angular.element('<div/>').addClass('wave');
rippler.css({
top: mY + 'px',
left: mX + 'px',
height: (height / 2) + 'px',
width: (height / 2) + 'px',
});
if (waveColor !== undefined || waveColor !== "") {
rippler.css('background-color', waveColor);
}
angular.element(elem).append(rippler);
$compile(elem.contents())(scope);
$timeout(function () {
angular.element(rippler).remove();
}, 500);
});
}
}
below is my component controller code.
verifyCtr.$inject=['$element','verifyService','$scope'];
function verifyCtr($element,verifyService,$scope){
console.log('verify component is up and working');
var $this=this;
var serviceObj={
baseUrlType:'recommender',
url:'https://httpbin.org/ip',
method:1,
data:{}
};
$this.$onInit=function(){
verifyService.getData(serviceObj,{
success:function(status,message,data){
$this.data=data;
},
error:function(status,message){
alert(status,'\n',message);
}
});
};
$this.$onChanges=function(changes){};
$this.$postLink=function(){
angular.element(document.querySelector('.addNewTag')).bind('click',function(){
console.log('hi there you clicked this btn');
});
};
$this.$onDestroy=function(){
angular.element(document.querySelector('.addNewTag')).unbind('click');
var removeListener=$scope.$on('someEvent',function(ev){});
removeListener();
};
}module.exports=verifyCtr;
when i run it. the component click event-listener is fired. but the directive fails to execute. i don't know whats causing this issue and i want both of them to work.
it took a while to figure it out.
document.querySelector('.class-name') ;
returns a array of html elements. and
angular.element(elem).bind()
works on one single angular element. so i had to use a unique way of identifying the element i,e by the Id. so what i did was
angular.element(document.querySelector('#id')).bind();
there is other ways of doing it by the classname also . we can itreate over the array and get our element and bind the event to it.

How to change the opacity on an element dynamically using javascript

i made a function that change the opacity of an element, but you know it is not working, Following is my code:
function _opacity(ele, opacity,addOpac , delay ){
ele = document.getElementById(ele);
var CurrentOpacity = ele.style.opacity,
ChangeInOpacity = setInterval(function(){
if (CurrentOpacity > opacity ) { decrease();};
if (CurrentOpacity < opacity) { increase();};
if (CurrentOpacity == opacity) { stopInc();};
}, delay),
increase = function(){
ele.style.opacity = CurrentOpacity;
CurrentOpacity = CurrentOpacity+addOpac;
},
decrease =function(){
ele.style.opacity = CurrentOpacity;
CurrentOpacity = CurrentOpacity-addOpac;
},
stopInc = function(){
clearInterval(ChangeInOpacity);
};
}
one of the foremost feature of this function is that is doesn't uses any loop.
this ideology of using setInterval works perfectly in changing the width and height of element. But here this function is not functioning.
What i know is that it is not adding any style attribute to the element which is passed to the above function
what is the mistake here because of which this is not working?
thanks in advance.
There are a few problems there:
To get the current opacity of the element, you need to use the getComputedStyle function (or currentStyle property on oldIE), not .style.opacity. The latter only has a value if it's been assigned explicitly, rather than implicitly through style sheets.
The value will be a string, so you need to convert it to a number.
It's unlikely that you'll exactly match the target opaccity, so you need to just stop when you cross the target.
You don't put ; at the end of if statements, so remove those.
You assign the opacity, but then increment it, and then later the incremented value is what you check to see if you're done, so even if it weren't for #3, you'd stop early.
In JavaScript, the overwhelming convention is to start local variable names with a lower-case letter. I changed the name of your timer handle to timer.
Your best bet is to figure out what direction you're going, then stop when you pass the target:
// Polyfill getComputedStyle for old IE
if (!window.getComputedStyle) {
window.getComputedStyle = function(element) {
return element.currentStyle;
}
}
// Your _opacity function
function _opacity(ele, opacity, addOpac, delay) {
var direction;
ele = document.getElementById(ele);
// Determine direction
direction = +getComputedStyle(ele).opacity < opacity ? 1 : -1;
var timer = setInterval(function() {
// Get the *computed* opacity
var current = +getComputedStyle(ele).opacity;
if (direction > 0) {
if (current < opacity) {
increase(current);
} else {
stopInc();
}
}
else {
if (current > opacity) {
decrease(current);
} else {
stopInc();
}
}
}, delay),
increase = function(current) {
// Increase, but don't go past target
ele.style.opacity = Math.min(current + addOpac, opacity);
},
decrease = function(current) {
// Decrease, but don't go past target
ele.style.opacity = Math.max(current - addOpac, opacity);
},
stopInc = function() {
clearInterval(timer);
};
};
// Run
_opacity("target", 0.3, 0.05, 50);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div id="target">this is the element</div>
you can do this:
ele.style.opacity = "0.2";// some desired value but string if for all browsers.
for more info see this post:Setting opacity of html elements in different browsers

JQuery If condition (specific for a content slider)

I am new at JQuery and I have a specific question about the IF-THEN-ELSE fork.
The big problem for me is the syntax of this (I suck at Javascript). It would help me if anyone can "translate" the pseudo code into a JQuery (or Javascript) valide code.
The pseudo code:
IF "#Contentshowroom" css "left" is NOT > 1960px
THEN
On Click "#Forwardbutton" DO
animate "#Contentshowroom" css "left" =+980px
ELSE You can not click on the "#Forwardbutton"
Place the if() statement in the click handler for #Forwardbutton to test the left position of #Contentshowroom.
If you're using jQuery:
$('#Forwardbutton').click(function() {
var $Content = $('#Contentshowroom');
if( $Content.offset().left <= 1960 ) {
$Content.animate({ left: '+= 980' });
}
});
So now when you click the Forwardbutton, it will check the left .offset() position of the Contentshowroom to see if it is less than or equal to 1960px. And if so, it will animate the left position an additional 980px.
jQuery's .offset() method gives you the top/left positions relative to the body. If you want it relative to its parent container, then use jQuery's .position() method.
click doc
animate doc
offset doc
$("#Forwardbutton").click( function( e ){
// lookup is safe, no noticable performance cost.
// though a reference makes it more losely coupled.
// I'll leave it at your discretion.
var target = $("#Contentshowroom")
// NOTE: the offset parent should have position relative or absolute.
, leftPos = target.offset().left;
if ( leftPos < 1960 ) {
target.animate({
left : leftPos + 980
}); // see docs to tweak animation
} // else do nothing.
} );
Could also use e.preventDefault(); , but don't if it's not needed, it will safe you headaches if you add more listeners to your buttons and find out they're not working.
// first store contentShowroom and it's left property to save getting > 1
var contentShowroom = $('#Contentshowroom');
var showroomLeft = contentShowroom.css('left');
var forwardButton = $('#Forwardbutton');
if (showroomLeft <= 1960){
forwardButton.click(function(){
contentShowroom.animate({left: showroomLeft + 980);
}
}
else {
forwardButton.unbind('click');
}
if this is to be run once at the beginning then
if ( $('#Contentshowroom').offset().left > 1960 )
{
$('#Forwardbutton').click( function(){
$('#Contentshowroom').animate({left:'+=980'});
} );
}
else
{
// if the #Contentshowroom is a link then
$('#Contentshowroom').removeAttr('href');
// if the #Contentshowroom is a button then
// $('#Contentshowroom').attr('disabled',true);
}

Javascript: IE Error, Firebug not erring. Where is it?

Again, I am working with code from my predecessor and am at a loss for this one. It appears to be a sampled navigation script. It is receiving an error in IE stating Object doesn't support this property or method. Here is what I have narrowed the error down to.
The function:
/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
*
* #param f onMouseOver function || An object with configuration options
* #param g onMouseOut function || Nothing (use configuration options object)
* #author Brian Cherne <brian#cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};
cfg=$.extend(cfg,g?{over:f,out:g}:f);
var cX,cY,pX,pY;
var track=function(ev){cX=ev.pageX;
cY=ev.pageY;
};
var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);
if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);
ob.hoverIntent_s=1;
return cfg.over.apply(ob,[ev]);
}else{pX=cX;
pY=cY;
ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);
},cfg.interval);
}};
var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);
ob.hoverIntent_s=0;
return cfg.out.apply(ob,[ev]);
};
var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;
while(p&&p!=this){try{p=p.parentNode;
}catch(e){p=this;
}}if(p==this){return false;
}var ev=jQuery.extend({},e);
var ob=this;
if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);
}if(e.type=="mouseover"){pX=ev.pageX;
pY=ev.pageY;
$(ob).bind("mousemove",track);
if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);
},cfg.interval);
}}else{$(ob).unbind("mousemove",track);
if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);
},cfg.timeout);
}}};
return this.mouseover(handleHover).mouseout(handleHover);
};
})(jQuery);
The document.ready line triggering the error:
var config = {
sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
interval: 50, // number = milliseconds for onMouseOver polling interval
over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
timeout: 200, // number = milliseconds delay before onMouseOut
out: megaHoverOut // function = onMouseOut callback (REQUIRED)
};
$("ul#topnav li .sub").css({'opacity':'0'});
$("ul#topnav li").hoverIntent(config);
I am at a loss as to how to resolve this and finally get this section fixed.
The two functions that are defined within document.ready.
function megaHoverOver(){
$(this).find(".sub").stop().fadeTo('fast', 1).show();
//Calculate width of all ul's
(function($) {
jQuery.fn.calcSubWidth = function() {
rowWidth = 0;
//Calculate row
$(this).find("ul").each(function() {
rowWidth += $(this).width();
});
};
})(jQuery);
if ( $(this).find(".row").length > 0 ) { //If row exists...
var biggestRow = 0;
//Calculate each row
$(this).find(".row").each(function() {
$(this).calcSubWidth();
//Find biggest row
if(rowWidth > biggestRow) {
biggestRow = rowWidth;
}
});
//Set width
$(this).find(".sub").css({'width' :biggestRow});
$(this).find(".row:last").css({'margin':'0'});
} else { //If row does not exist...
$(this).calcSubWidth();
//Set Width
$(this).find(".sub").css({'width' : rowWidth});
}
}
function megaHoverOut(){
$(this).find(".sub").stop().fadeTo('fast', 0, function() {
$(this).hide();
});
}
I'm able to run that code without errors (see http://jsfiddle.net/veHEY/). It looks like the issue might be in the megaHoverOver and megaHoverOut functions that you're passing in through the configuration object. Do you have the code for those functions?
Previously:
The problem is almost certainly
opacity, which is not supported in
IE. Check out this nice quirksmode
article on cross-browser opacity
issues.
Correction: As #patrick rightly points out, and backs up with a source code reference to boot, jQuery is smart enough to automatically deal with IE's own special brands of opacity handling. Whatever the OP's problem is, this is not the answer.

Categories