Asked  7 Months ago    Answers:  5   Viewed   29 times

I want to create common header and footer pages that are included on several html pages.

I'd like to use javascript. Is there a way to do this using only html and JavaScript?

I want to load a header and footer page within another html page.

 Answers

93

You can accomplish this with jquery.

Place this code in index.html

<html>
<head>
<title></title>
<script
    src="https://code.jquery.com/jquery-3.3.1.js"
    integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
    crossorigin="anonymous">
</script>
<script> 
$(function(){
  $("#header").load("header.html"); 
  $("#footer").load("footer.html"); 
});
</script> 
</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>

and put this code in header.html and footer.html, at the same location as index.html

<a href="http://www.google.com">click here for google</a>

Now, when you visit index.html, you should be able to click the link tags.

Tuesday, June 1, 2021
 
anjan
answered 7 Months ago
21

The first line of your stack trace tells you exactly what you are doing wrong:

02-06 00:37:14.265: ERROR/AndroidRuntime(1607): FATAL EXCEPTION: main
02-06 00:37:14.265: ERROR/AndroidRuntime(1607): java.lang.IllegalStateException: Could not find a method postData(View) in the activity class com.nathanhunston.heat.Main for onClick handler on view class android.widget.Button with id 'dropLocBtn'

That is because you do not have a View parameter in your postData() method declaration.

Wednesday, March 31, 2021
 
Shobit
answered 9 Months ago
74

Using IntersectionObserver API

The IntersectionObserver API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

Here's an example that triggers a classList toggle when an Element is in viewport:

const inViewport = (entries, observer) => {
  entries.forEach(entry => {
    entry.target.classList.toggle("is-inViewport", entry.isIntersecting);
  });
};

const Obs = new IntersectionObserver(inViewport);
const obsOptions = {}; //See: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Intersection_observer_options

// Attach observer to every [data-inviewport] element:
const ELs_inViewport = document.querySelectorAll('[data-inviewport]');
ELs_inViewport.forEach(EL => {
  Obs.observe(EL, obsOptions);
});
[data-inviewport] { /* THIS DEMO ONLY */
  width:100px; height:100px; background:#0bf; margin: 150vh 0; 
}

/* inViewport */

[data-inviewport="scale-in"] { 
  transition: 2s;
  transform: scale(0.1);
}
[data-inviewport="scale-in"].is-inViewport { 
  transform: scale(1);
}

[data-inviewport="fade-rotate"] { 
  transition: 2s;
  opacity: 0;
}
[data-inviewport="fade-rotate"].is-inViewport { 
  transform: rotate(180deg);
  opacity: 1;
}
Scroll down...
<div data-inviewport="scale-in"></div>
<div data-inviewport="fade-rotate"></div>

Observer Options

To define another parent reference element use the root option inside the Observable options Object. At your disposition there's also rootMargin and the super useful threshold option

const obsOptions = {
  // Default is null (Browser viewport). Set a specific parent element:
  root: document.querySelector('#someSpecificParent'),
  // add 40px inner "margin" area at which the observer starts to calculate:
  rootMargin: '40px', 
  // Default is 0.0 meaning the callback is called as soon 1 pixel is inside the viewport.  
  // Set to 1.0 to trigger a callback when 100% of the target element is inside the viewport,   
  // or i.e: 0.5 when half of the target element is visible:
  threshold: 0.5, 
};

See another interesting use case that uses the IntersectionObserver API's threshold option.

Additional read:

  • w3.org
  • developer.mozilla.org
  • caniuse.com IE browser

Using the native IntersectionObserver API is the most performant way to tackle this problem.
If you want an idea on how we tackled similar needs in the past see this answer with a small custom plugin as an example.

Sunday, June 13, 2021
 
adjco
answered 6 Months ago
71

Your class should implement ColorPickerDialog.OnColorChangedListener

  public class MainActivity implements ColorPickerDialog.OnColorChangedListener
  {
       private Paint mPaint;  

        mPaint = new Paint();
       // on button click
        new ColorPickerDialog(this, this, mPaint.getColor()).show();

  }

ColorPicker Dialog

public class ColorPickerDialog extends Dialog {

public interface OnColorChangedListener {
    void colorChanged(int color);
}

private OnColorChangedListener mListener;
private int mInitialColor;

private static class ColorPickerView extends View {
    private Paint mPaint;
    private Paint mCenterPaint;
    private final int[] mColors;
    private OnColorChangedListener mListener;

    ColorPickerView(Context c, OnColorChangedListener l, int color) {
        super(c);
        mListener = l;
        mColors = new int[] {
            0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00,
            0xFFFFFF00, 0xFFFF0000
        };
        Shader s = new SweepGradient(0, 0, mColors, null);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setShader(s);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(32);

        mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCenterPaint.setColor(color);
        mCenterPaint.setStrokeWidth(5);
    }

    private boolean mTrackingCenter;
    private boolean mHighlightCenter;

    @Override
    protected void onDraw(Canvas canvas) {
        float r = CENTER_X - mPaint.getStrokeWidth()*0.5f;

        canvas.translate(CENTER_X, CENTER_X);

        canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
        canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);

        if (mTrackingCenter) {
            int c = mCenterPaint.getColor();
            mCenterPaint.setStyle(Paint.Style.STROKE);

            if (mHighlightCenter) {
                mCenterPaint.setAlpha(0xFF);
            } else {
                mCenterPaint.setAlpha(0x80);
            }
            canvas.drawCircle(0, 0,
                              CENTER_RADIUS + mCenterPaint.getStrokeWidth(),
                              mCenterPaint);

            mCenterPaint.setStyle(Paint.Style.FILL);
            mCenterPaint.setColor(c);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(CENTER_X*2, CENTER_Y*2);
    }

    private static final int CENTER_X = 100;
    private static final int CENTER_Y = 100;
    private static final int CENTER_RADIUS = 32;

    private int floatToByte(float x) {
        int n = java.lang.Math.round(x);
        return n;
    }
    private int pinToByte(int n) {
        if (n < 0) {
            n = 0;
        } else if (n > 255) {
            n = 255;
        }
        return n;
    }

    private int ave(int s, int d, float p) {
        return s + java.lang.Math.round(p * (d - s));
    }

    private int interpColor(int colors[], float unit) {
        if (unit <= 0) {
            return colors[0];
        }
        if (unit >= 1) {
            return colors[colors.length - 1];
        }

        float p = unit * (colors.length - 1);
        int i = (int)p;
        p -= i;

        // now p is just the fractional part [0...1) and i is the index
        int c0 = colors[i];
        int c1 = colors[i+1];
        int a = ave(Color.alpha(c0), Color.alpha(c1), p);
        int r = ave(Color.red(c0), Color.red(c1), p);
        int g = ave(Color.green(c0), Color.green(c1), p);
        int b = ave(Color.blue(c0), Color.blue(c1), p);

        return Color.argb(a, r, g, b);
    }

    private int rotateColor(int color, float rad) {
        float deg = rad * 180 / 3.1415927f;
        int r = Color.red(color);
        int g = Color.green(color);
        int b = Color.blue(color);

        ColorMatrix cm = new ColorMatrix();
        ColorMatrix tmp = new ColorMatrix();

        cm.setRGB2YUV();
        tmp.setRotate(0, deg);
        cm.postConcat(tmp);
        tmp.setYUV2RGB();
        cm.postConcat(tmp);

        final float[] a = cm.getArray();

        int ir = floatToByte(a[0] * r +  a[1] * g +  a[2] * b);
        int ig = floatToByte(a[5] * r +  a[6] * g +  a[7] * b);
        int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);

        return Color.argb(Color.alpha(color), pinToByte(ir),
                          pinToByte(ig), pinToByte(ib));
    }

    private static final float PI = 3.1415926f;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX() - CENTER_X;
        float y = event.getY() - CENTER_Y;
        boolean inCenter = java.lang.Math.sqrt(x*x + y*y) <= CENTER_RADIUS;

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mTrackingCenter = inCenter;
                if (inCenter) {
                    mHighlightCenter = true;
                    invalidate();
                    break;
                }
            case MotionEvent.ACTION_MOVE:
                if (mTrackingCenter) {
                    if (mHighlightCenter != inCenter) {
                        mHighlightCenter = inCenter;
                        invalidate();
                    }
                } else {
                    float angle = (float)java.lang.Math.atan2(y, x);
                    // need to turn angle [-PI ... PI] into unit [0....1]
                    float unit = angle/(2*PI);
                    if (unit < 0) {
                        unit += 1;
                    }
                    mCenterPaint.setColor(interpColor(mColors, unit));
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                if (mTrackingCenter) {
                    if (inCenter) {
                        mListener.colorChanged(mCenterPaint.getColor());
                    }
                    mTrackingCenter = false;    // so we draw w/o halo
                    invalidate();
                }
                break;
        }
        return true;
    }
}

public ColorPickerDialog(Context context,
                         OnColorChangedListener listener,
                         int initialColor) {
    super(context);

    mListener = listener;
    mInitialColor = initialColor;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    OnColorChangedListener l = new OnColorChangedListener() {
        public void colorChanged(int color) {
            mListener.colorChanged(color);
            dismiss();
        }
    };

    setContentView(new ColorPickerView(getContext(), l, mInitialColor));
    setTitle("Pick a Color");
}

You have to choose the color and click the center circle to pick the color. Set the color to your paint object and use the same to draw.

Snap shot

enter image description here

Edit 2:

Source code can be found at https://code.google.com/p/android-color-picker/

Another ColorPickerDialog

   public class ColorPickerDialog extends AlertDialog implements
    ColorPickerView.OnColorChangedListener {

private ColorPickerView mColorPicker;

private ColorPanelView mOldColor;
private ColorPanelView mNewColor;

private OnColorChangedListener mListener;

public ColorPickerDialog(Context myDrawingMenuOptionEventsListener, int initialColor) {
    super(myDrawingMenuOptionEventsListener);

    init(initialColor);
}

private void init(int color) {
    // To fight color branding.
    getWindow().setFormat(PixelFormat.RGBA_8888);

    setUp(color);

}

private void setUp(int color) {
    LayoutInflater inflater = (LayoutInflater) getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.dialog_color_picker, null);
    layout.setBackgroundColor(Color.WHITE);
    setView(layout);

    setTitle("Choose a Color");
    // setIcon(android.R.drawable.ic_dialog_info);

    mColorPicker = (ColorPickerView) layout
            .findViewById(R.id.color_picker_view);
    mOldColor = (ColorPanelView) layout.findViewById(R.id.old_color_panel);
    mNewColor = (ColorPanelView) layout.findViewById(R.id.new_color_panel);

    ((LinearLayout) mOldColor.getParent()).setPadding(Math
            .round(mColorPicker.getDrawingOffset()), 0, Math
            .round(mColorPicker.getDrawingOffset()), 0);

    mColorPicker.setOnColorChangedListener(this);

    mOldColor.setColor(color);
    mColorPicker.setColor(color, true);

}

@Override
public void onColorChanged(int color) {

    mNewColor.setColor(color);

    if (mListener != null) {
        mListener.onColorChanged(color);
    }

}

public void setAlphaSliderVisible(boolean visible) {
    mColorPicker.setAlphaSliderVisible(visible);
}

public int getColor() {
    return mColorPicker.getColor();
}

 }

Usage :

        final ColorPickerDialog d= new ColorPickerDialog(ActivityName.this,0xffffffff);
                d.setAlphaSliderVisible(true);

                d.setButton("Ok", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        mPaint.setColor(d.getColor());

                    }
                });

                d.setButton2("Cancel", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                d.show();

Snap shot:

Snap2

In the above choose the color on the right bar. You also make a choice how dark or light the color choosen should be. Click ok to set the paint to your paint object and use the same to draw. Cancel will dismiss the color picker dialog.

Edit 3:

Only change instead of clear function i have added color picker on click of clear button.

   public class MainActivity extends Activity implements ColorPickerDialog.OnColorChangedListener {

DrawingView dv ;
RelativeLayout rl;   
private Paint       mPaint;
private MaskFilter  mEmboss;
private MaskFilter  mBlur;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dv = new DrawingView(this);
    setContentView(R.layout.activity_main);
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(Color.GREEN);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(12);
    rl = (RelativeLayout) findViewById(R.id.rl);
    rl.addView(dv);
    Button b = (Button) findViewById(R.id.button1);
    //b.setText(R.string.France);
    Button b1 = (Button) findViewById(R.id.button2);
    rl.setDrawingCacheEnabled(true);
    b.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
              // dv.clear();    
             new ColorPickerDialog(MainActivity.this, MainActivity.this, mPaint.getColor()).show();


        }

    });

    b1.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            AlertDialog.Builder editalert = new AlertDialog.Builder(MainActivity.this);
            editalert.setTitle("Please Enter the name with which you want to Save");
            final EditText input = new EditText(MainActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.FILL_PARENT);
            input.setLayoutParams(lp);
            editalert.setView(input);
            editalert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    rl.setDrawingCacheEnabled(true);
                    String name= input.getText().toString();
                    Bitmap bitmap =rl.getDrawingCache();
                    String root = Environment.getExternalStorageDirectory().toString();
                    File myDir = new File(root + "/MyDraw");    
                    myDir.mkdirs();
                    File file = new File (myDir, name+".png");
                    if (file.exists ()) file.delete ();         
                    try 
                    {
                        if(!file.exists())
                    {
                        file.createNewFile();
                    }
                        FileOutputStream ostream = new FileOutputStream(file);
                        bitmap.compress(CompressFormat.PNG, 10, ostream);
                       // System.out.println("saving......................................................"+path);
                        ostream.close();
                        rl.invalidate();                            
                    } 
                    catch (Exception e) 
                    {
                        e.printStackTrace();
                    }finally
                    {

                       rl.setDrawingCacheEnabled(false);                            
                    }
                }
            });
            editalert.show();   
        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

 public class DrawingView extends View {

        private static final float MINP = 0.25f;
        private static final float MAXP = 0.75f;
        private Bitmap  mBitmap;
        private Canvas  mCanvas;
        private Path    mPath;
        private Paint   mBitmapPaint;
        Context context;
        private Paint circlePaint;
        private Path circlePath;

        public DrawingView(Context c) {
        super(c);
        context=c;
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);  
         circlePaint = new Paint();
         circlePath = new Path();
         circlePaint.setAntiAlias(true);
         circlePaint.setColor(Color.BLUE);
         circlePaint.setStyle(Paint.Style.STROKE);
         circlePaint.setStrokeJoin(Paint.Join.MITER);
         circlePaint.setStrokeWidth(4f); 

        }

        @Override
         protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);

        }

        @Override
        protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

        canvas.drawPath(mPath, mPaint);

        canvas.drawPath(circlePath, circlePaint);
        }

        private float mX, mY;
        private static final float TOUCH_TOLERANCE = 4;

        private void touch_start(float x, float y) {
        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
        }
        private void touch_move(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
            mX = x;
            mY = y;

             circlePath.reset();
             circlePath.addCircle(mX, mY, 30, Path.Direction.CW); 
             invalidate();

        }
        }
        private void touch_up() {
        mPath.lineTo(mX, mY);
        circlePath.reset();
        // commit the path to our offscreen
        mCanvas.drawPath(mPath, mPaint);
        // kill this so we don't double draw
        mPath.reset();

        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                touch_up();
                invalidate();
                break;
        }
        return true;
        }  
        }
@Override
public void colorChanged(int color) {
    // TODO Auto-generated method stub
    mPaint.setColor(color);
}
  }

enter image description here

Wednesday, June 30, 2021
 
Arman
answered 6 Months ago
83

You need a top position for the sidebar that is the amount of space that you allow it to go upwards.

A little javascript funcion can calculate this easily:

function set ()  {
    var sidebar = document.getElementById("sidebar");
    var sidebarHeight = sidebar.clientHeight;
    var availableHeight = window.innerHeight;
    var sidebarTop =  availableHeight - sidebarHeight - 20;
    // 20px is the amount of space that will be left under the bottom of the sidebar
    // at the sticky position
    sidebar.style.top = sidebarTop + "px";
}
* {
  font-family: "Courier New", Courier, monospace;
  color: #fff;
  text-align: center;
}

.container {
  height: 2000px;
  position: relative;
}

.topbar {
  height: 50px;
  line-height: 50px;
  background: #D16666;
  position: -webkit-sticky;
  position: sticky;
  border-radius: 5px;
  top: 0px;
  z-index: 10;
}

.sidebar {
  position: -webkit-sticky;
  position: sticky;
  border-radius: 5px;
  top: 60px;
  height: 1000px;
  line-height: 1000px;
  background: #B6C649;
  border-radius: 5px;
  position: -webkit-sticky;
  position: sticky;
  margin-top: 10px;
}

.row {
  margin-left: 0;
  margin-right: 0;
  position: relative;
}


.main-content {
  height: 1800px;
  line-height: 1800px;
  background: #2C4251;
  border-radius: 5px;
  top: 10px;
}

.col-8 {
  top: 10px;
  padding: 0;
  padding-left: 0 !important;
}

button {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 30px;
    background-color:blue;
    z-index: 10;
}
<head>
  <link href="https://static.aftertutor.com/css/bootstrap.min.css" rel="stylesheet" />
</head>

  <div class="container">
    <div class="topbar">Topbar</div>
    <div class="row">
      <div class="col-4">
        <div class="sidebar" id="sidebar">Sidebar</div>
      </div>
      <div class="col-8">
        <div class="main-content">Main Content</div>
      </div>
    </div>
  </div>
  <button onclick="set();">click me</button>
Monday, October 4, 2021
 
neon29
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share